将App.xaml样式移动到资源字典

时间:2012-06-15 13:39:01

标签: silverlight xaml resources app.xaml application-resource

我有一个自定义控件,它使用app.xaml中链接的资源字典中的样式。如果我关闭该链接并将链接添加到包含该控件的页面,则该链接不起作用。这是为什么?为什么我的控件(一个dll)需要样式在app.xaml中,而不只是在包含控件的页面上?

2 个答案:

答案 0 :(得分:3)

  

为什么我的控件(dll)需要样式位于app.xaml中,而不仅仅是控件所包含的页面?

自定义控件需要默认样式。此默认样式在构造函数中设置。 例如:

public CustomControl()
{
    DefaultStyleKey = typeof(CustomControl);
}

设置此项时,它会在此样式的包含程序集中查找。如果控件在应用程序中,则它在App.xaml中查找。如果控件位于类库中,它将在文件Generic.xaml中查找,该文件必须放在文件夹“Themes”中。您无需将样式放在这些文件中的任何一个中。您可以创建一个包含该样式的单独文件,并从App.xaml或Themes / Generic.xaml引用它(基于定义控件的位置)。为此,您可以在其中一个文件中创建MergedDictionary。如果您的控件是在您的应用程序中定义的,那么您可以

<Application x:Class="MyApp.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"       
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <!--Application Resources-->
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Controls/CustomControl.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    <Application.Resources>
</Application>

如果您的控件是在类库中定义的,则Themes / Generic.xaml应该如下所示

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="/My.Custom.Assembly;component/FolderLocationOfXaml/CustomControl.xaml" />
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

无论您的自定义控件放在何处,xaml都将始终显示相同的

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:My.Custom.Assembly.Controls">
        <Style TargetType="local:CustomControl">
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:CustomControl">
                    <Grid>
                        <! -- Other stuff here -->
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

如果未定义此默认样式,则无法确定要覆盖的样式。定义默认样式后,您可以更改应用程序中的样式或使用控件的任何其他样式。

答案 1 :(得分:0)

尝试将样式移动到控件中以验证所有必需的引用是否适合您的控件使用字典中的项目。 确保包含UserControl的项目具有对包含资源字典的项目的引用。 验证字典的源路径:

<ResourceDictionary Source="/AssemblyName;component/StylesFolderName/ResourceDictionaryName.xaml" />

相关问题