繁体   English   中英

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

[英]Moving App.xaml Styles to Resource Dictionary

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

为什么我的控件(一个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>

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM