Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 默认样式不适用于子类_C#_Wpf_Xaml - Fatal编程技术网

C# 默认样式不适用于子类

C# 默认样式不适用于子类,c#,wpf,xaml,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:testWpfStyl

我有一个奇怪的场景,涉及覆盖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>

我希望StackPanel中的控件YellowLabel为蓝色,外部的控件YellowLabel为红色,但两者均为黑色。子类是否有一种方法可以采用其父类的默认样式?

实际上,WPF就是这样工作的。我已经讨论了WPF样式(主要是关于主题属性如何工作),但是问题1的场景1的基本问题与您描述的相同。也就是说,隐式局部样式是使用实际的类类型定位的,与DefaultStyleKey没有关系。DefaultStyleKey仅在定位默认样式(即基于当前OS主题应用于控件的样式和控件的默认generic.xaml)时使用。解决这个问题的一个简单方法是将派生控件的样式(例如,在其ctor中)设置为对基类样式的DynamicSource引用。例如

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

您通常不会对WPF UI元素进行子类化。也就是说,您需要
DefaultStyleKeyProperty.OverrideMetadata()
。默认样式只应用于精确TargetType的元素,对此您无能为力。尝试按照HighCore的建议覆盖
SomeLabel
的默认样式,“YellowLabel”将继承相同的样式。
this.SetResourceReference(StyleProperty, typeof(SomeLabel));