覆盖应用程序范围的样式 [英] Overriding application wide style
问题描述
我想为应用程序中的textblock定义一个全局样式,但是我也希望能够覆盖此默认样式.我一直认为样式的局部优先级要比全局优先级高,但是事实并非如此?
I want to define a global style for textblock in the application but I also want to be able to override this default style. I always thought that the local override of style has more priority than the global one but it doesn't seems to be the case?
在下面的示例中,当我期望按钮的内容为"Aqua"时,其内容为"Test"的按钮将具有"Red"的前景.如果我在Application.Resources中删除全局样式,那么它将起作用.我想念什么吗?
In the following example, the Button with content "Test" will have a "Red" foreground when I expect it to be "Aqua". If I remove the global style in Application.Resources, than it will works. Did I'm missing something?
App.xaml
<Application x:Class="ContextMenuTest.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Foreground" Value="Red" />
</Style>
</Application.Resources>
MainWindow.xaml
MainWindow.xaml
<Window x:Class="ContextMenuTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style TargetType="{x:Type MenuItem}" x:Key="DefaultMenuItemStyle">
<Setter Property="Foreground" Value="DarkGreen" />
</Style>
<Style TargetType="{x:Type Button}" x:Key="DefaultButtonStyle">
<Setter Property="Foreground" Value="DarkGreen" />
</Style>
</Window.Resources>
<Grid Background="Black">
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Header="Menu 1" Style="{StaticResource DefaultMenuItemStyle}" />
<MenuItem Header="Menu 2" Style="{StaticResource DefaultMenuItemStyle}" />
<MenuItem Header="Menu 3" Style="{StaticResource DefaultMenuItemStyle}" />
<MenuItem Header="Menu 4" Style="{StaticResource DefaultMenuItemStyle}" />
<MenuItem Header="Menu 5" Style="{StaticResource DefaultMenuItemStyle}" />
</ContextMenu>
</Grid.ContextMenu>
<Button Content="Test" Style="{StaticResource DefaultButtonStyle}" Foreground="Aqua" />
</Grid>
推荐答案
在App.xaml
中定义的隐式TextBlock
将不会被其他TextBlock
样式覆盖.因此,建议您将默认的TextBlock
样式移至例如<Window.Resources>
.
Implicit TextBlock
defined in App.xaml
will not be overrided by other TextBlock
styles. It's therefore recommended that you move your default TextBlock
style to for example <Window.Resources>
.
有关此的更多信息,请参考以下链接.
Please refer to the following links for more information about this.
Application.Resources与Window.Resources中的隐式样式?
跳过App.xaml中的属性"设置: 或者根本不定义任何隐式的TextBlock
样式.为每个Control
定义一个默认的Style
.
Or simply don't define any implicit TextBlock
style. Define a default Style
for each Control
instead.
这篇关于覆盖应用程序范围的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!