首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将App.xaml样式移动到资源字典

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

Stack Overflow用户
提问于 2012-06-15 21:39:01
回答 2查看 6.1K关注 0票数 1

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

EN

回答 2

Stack Overflow用户

发布于 2012-06-15 23:59:31

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

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

代码语言:javascript
复制
public CustomControl()
{
    DefaultStyleKey = typeof(CustomControl);
}

设置后,它将在包含此样式的程序集中进行查找。如果控件在应用程序中,则在App.xaml中查找。如果控件在类库中,则它在一个文件Generic.xaml中查找,该文件必须放在"Themes“文件夹中。您不需要将样式放置在这两个文件中。可以创建包含该样式的单独文件,并从App.xaml或Themes/Generic.xaml (基于定义控件的位置)引用该样式。为此,您需要在其中一个文件中创建一个MergedDictionary。如果您的控件是在应用程序中定义的,您将执行以下操作

代码语言:javascript
复制
<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>

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

代码语言:javascript
复制
<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看起来都是一样的

代码语言:javascript
复制
<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>

如果未定义此默认样式,则无法确定要覆盖的样式。一旦定义了默认样式,您就可以在应用程序内或使用控件的任何其他地方更改样式。

票数 3
EN

Stack Overflow用户

发布于 2012-06-15 23:22:47

请尝试将样式移动到控件中,以验证控件使用字典中的项所需的所有引用是否都已就位。确保包含UserControl的项目引用了包含资源字典的项目。验证字典的源路径:

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11051750

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档