gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:42:52 25 4
gpt4 key购买 nike

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

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