因此,我们尝试通过更改 generic.xaml 中的默认样式来重新模板化一些库存 wpf 控件
当我们通常这样做时,我们对控件进行子类化,然后在其静态初始值设定项中覆盖子类化控件的默认样式键。但是,我们现在尝试重写基本控件而不对其进行子类化。这样,公司中使用库存 wpf 控件的任何人都将默认获得我们的新样式。
不过我似乎无法让它发挥作用。
在我的沙箱应用程序中,这是我们实际问题的淡化版本,我有以下内容。
MainWindow.xaml
<StackPanel>
<TextBlock>It doesn't work</TextBlock>
<local:CustomTextBlock>It works</local:CustomTextBlock>
</StackPanel>
Themes/Generic.xaml
<Style TargetType="{x:Type TextBlock}">
<Setter Property="FontSize" Value="100" />
</Style>
<Style TargetType="{x:Type test:CustomTextBlock}">
<Setter Property="FontSize" Value="100" />
</Style>
CustomTextBlock.cs
public class CustomTextBlock : TextBlock
{
static CustomTextBlock()
{
Type _CustomTextBlock = typeof(CustomTextBlock);
DefaultStyleKeyProperty.OverrideMetadata(
_CustomTextBlock,
new FrameworkPropertyMetadata(_CustomTextBlock));
}
}
这会导致显示此内容。
我的理论是,WPF 引擎忽略了我们的样式,因为默认样式键是 A: not overridden 或 B: 首先在 generic.xaml 中查找样式。
我的问题是,有解决办法吗?我的假设正确吗?
更新:
根据引用源,在这种情况下,TextBlock.cs 的库存 wpf 控件中的默认样式键被覆盖
Reference Source TextBlock.cs (第 346 行)
最佳答案
要实现此目的,您可以将样式直接放入 App.xaml 中或放入单独的 ResourceDictionary(名为 DefaultStyles.xaml)中。
直接放入 App.xaml 中非常简单,只需将样式放入 Resources 元素中即可。
如果要将样式放入文件中(如果您想要多个应用程序或多个程序集中的样式,这非常有用),请将其添加到 App.xaml 的 MergedDictionaries 中
<Application x:Class="MyAwesomeApp"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Themes/DefaultStyles.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
这假设您将文件 DefaultStyles 放入 Themes 文件夹中。如果它在另一个程序集中,您将执行以下操作:
<ResourceDictionary Source="/Company.Controls.UI;component/DefaultStyles.xaml"/>
关于c# - 无法覆盖 generic.xaml 中 wpf 控件的默认样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40615818/