【问题标题】:Default styles do not apply to subclasses默认样式不适用于子类
【发布时间】:2013-05-22 03:10:55
【问题描述】:

我有一个奇怪的场景,涉及覆盖 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 UI 元素。话虽如此,您需要DefaultStyleKeyProperty.OverrideMetadata()。谷歌一下。
  • 一个默认样式只适用于精确 TargetType 的元素,你无能为力。尝试按照 HighCore 的建议覆盖 SomeLabel 的默认样式,“YellowLabel”将继承相同的样式。

标签: c# wpf xaml


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2017-02-02
    • 2016-12-12
    • 2017-01-22
    • 2020-11-17
    • 2018-11-02
    • 2019-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多