c# - 合并字典中的 WPF 覆盖样式

标签 c# wpf resourcedictionary

在我的字典文件中有

<Style TargetType="{x:Type Label}" BasedOn="{StaticResource {x:Type Label}}">
    <Setter Property="Foreground" Value="White" />
    <Setter Property="Background" Value="Black" />
</Style>

在我的 Window xaml 文件中有

    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/XXX;component/XXX.xaml"/>
            </ResourceDictionary.MergedDictionaries>

            <Style TargetType="Label" BasedOn="{StaticResource {x:Type Label}}">
                <Setter Property="FontSize" Value="20"/>
                <Setter Property="VerticalAlignment" Value="Center"/>
            </Style>
        </ResourceDictionary>
    </Window.Resources>

在设计器中我可以看到标签有黑色背景和白色前景,但在运行时它有默认的黑色前景和透明背景。很明显,我想继承字典样式,但它不起作用。我在那里做错了什么吗?我正在使用 VS 2013 和 .NET 4.5

编辑: 如果我删除 Windows.Resources 中的样式,则将应用字典样式。如果我将样式从 Windows Resource 移动到包含一些标签的 StackPanel.Resource,那么继承工作正常

最佳答案

根据 MSDN,Merged Resource Dictionaries :

如果在主字典和合并的字典中定义了键,则返回的资源将来自主字典。

根据这个规则,你的第二个样式最先被找到。然后该样式引用具有相同 {x:Type Label} 键的样式。出于某种原因,解析为 null。然而,检查第一种样式表明其 BasedOn 引用已按预期解析为默认标签样式。当两种样式都被赋予相同的显式键时,也会发生同样的情况。然而,当他们被赋予不同的 key 时,一切都按预期工作。

我的猜测是第二种样式会影响第一种样式。也许 BasedOn 引用已解析为样式本身,但为了防止循环依赖,它被设置为 null。

我个人会使用显式键。对于需要应用于特定类型的所有元素但在某些情况下仍需要覆盖的样式,我会将其分为两种样式:

// The actual style, with all its setters, is given a descriptive name:
<Style x:Key="DescriptiveName" TargetType="Label" BasedOn="{StaticResource {x:Type Label}}">
    // Setters go here
</Style>

// A 'dummy' style that references the above style.
// Its sole purpose is to apply the style to all elements of the target type.
<Style TargetType="Label" BasedOn="{StaticResource DescriptiveName}" />

当你需要覆盖样式时,你可以通过它的名字明确地引用它:

<Style TargetType="Label" BasedOn="{StaticResource DescriptiveName}">
    // Overriding setters go here
</Style>

关于c# - 合并字典中的 WPF 覆盖样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25858473/

相关文章:

C# 生成查询以将 DateTime 与 SQL Nvarchar 日期列进行比较

c# - 来自一个页面的多个 AJAX 请求的 ASP.NET MVC HTML.AntiForgeryToken()

wpf - 如何制作可以比其父项更宽的 TextBox?

c# - 如何为 PathGeometry 设置动画以使其缓慢显示?

c# - WPF 的高 CPU 使用率

wpf - 将一个大 XAML 拆分为多个 Sub-XAML 文件

c# - 将画笔的 ResourceDictionary 获取到 ItemsList 中

c# - XML 错误 : There are multiple root elements

c# - 在 WPF 中将 ResourceDictionary 与其他样式一起使用

c# - 在集合中找不到参数 "created_on"