gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:55:15 24 4
gpt4 key购买 nike

在我的字典文件中有

<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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com