默认样式不适用于子类

问题描述 投票:0回答:2
c# wpf xaml
2个回答
12
投票

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

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

0
投票

您可以使用

inherit
样式
BasedOn
在YellowLabel上的样式,如下

<Window.Resources>
    <Style TargetType="local:SomeLabel">
        <Setter Property="Foreground" Value="Red" />
    </Style>
    <!-- Inherit the style for Label -->
    <Style TargetType="local:YellowLabel" BasedOn="{StaticResource {x:Type local:SomeLabel}}"></Style>
</Window.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <local:SomeLabel Grid.Row="0">This should be red.</local:SomeLabel>
    <local:YellowLabel Grid.Row="1">This should be red.</local:YellowLabel>
    <StackPanel Grid.Row="2">
        <StackPanel.Resources>
            <Style TargetType="local:SomeLabel">
                <Setter Property="Foreground" Value="Blue" />
            </Style>
            <!-- Inherit the style for Label -->
            <Style TargetType="local:YellowLabel" BasedOn="{StaticResource {x:Type local:SomeLabel}}"></Style>
        </StackPanel.Resources>
        <local:SomeLabel>This should be blue.</local:SomeLabel>
        <local:YellowLabel>This should be blue.</local:YellowLabel>
    </StackPanel>
</Grid>

您得到所需的输出:

© www.soinside.com 2019 - 2024. All rights reserved.