c# - 默认样式不适用于子类

标签 c# wpf xaml

我有一个奇怪的场景涉及覆盖 WPF 中的默认样式并将它们应用于子类。这不可能吗?例如,我有以下代码:

<Window x:Class="TestWPFStyling.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:testWpfStyling="clr-namespace:TestWPFStyling"
        Title="MainWindow" Height="350" Width="525" Background="White">
    <Window.Resources>
        <Style TargetType="testWpfStyling:SomeLabel">
            <Setter Property="Foreground" Value="Red" />
        </Style>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <testWpfStyling:SomeLabel Grid.Row="0">This should be red.</testWpfStyling:SomeLabel>
        <testWpfStyling:YellowLabel Grid.Row="1">This should be red.</testWpfStyling:YellowLabel>
        <StackPanel Grid.Row="2">
            <StackPanel.Resources>
                <Style TargetType="testWpfStyling:SomeLabel">
                    <Setter Property="Foreground" Value="Blue" />
                </Style>
            </StackPanel.Resources>
            <testWpfStyling:SomeLabel>This should be blue.</testWpfStyling:SomeLabel>
            <testWpfStyling:YellowLabel>This should be blue.</testWpfStyling:YellowLabel>
        </StackPanel>

    </Grid>
</Window>

有了这个代码隐藏:

namespace TestWPFStyling
{
    public partial class MainWindow : Window
    {
    }

    public class SomeLabel : Label
    {
    }

    public class YellowLabel : SomeLabel
    {
    }
}

我希望 StackPanel 中的控件 YellowLabel 的颜色为蓝色,而外面的控件为红色,但它们都是黑色的。有没有办法让子类采用其父类的默认样式?

最佳答案

实际上这就是 WPF 的工作原理。我有 a blog post讨论 WPF 样式(主要是关于我们的 Theme 属性如何工作),但问题 1 的场景 1 的基本问题与您所描述的相同。也就是说,隐式本地样式使用实际类类型定位,与 DefaultStyleKey 无关。 DefaultStyleKey 仅在查找默认样式时使用(即基于当前操作系统主题和控件的默认 generic.xaml 应用于控件的样式)。解决此问题的一种简单方法是将派生控件的样式(例如在其构造函数中)设置为对基类样式的 DynamicResource 引用。例如

this.SetResourceReference(StyleProperty, typeof(SomeLabel));

关于c# - 默认样式不适用于子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16677479/

相关文章:

wpf - 如何在 XAML 绑定(bind)中使用 quote "字符?

xaml - Xamarin Forms 药丸按钮

c# - ConcurrentQueue<T>.TryPeek() 的用例是什么?

c# - 强类型 View 和共享 View

c# - 为什么我的所有换行符都从 "/r/n"更改为 "/n/",我该如何阻止这种情况发生?

c# - WPF、ObservableCollection/BindingList 绑定(bind)到 ListView

silverlight - 在设计模式下将数据上下文绑定(bind)到另一个 View 模型

c# - 整数上的 Mongo C# 过滤器包含

c# - 字节数组到字节转换错误

c# - 任务中的 ShowDialog 方法