我想为应用程序中的文本块定义全局样式,但我也希望能够覆盖此默认样式。我一直认为样式的本地覆盖比全局覆盖具有更高的优先级,但似乎并非如此?
在下面的示例中,当我希望它是“Aqua”时,内容为“Test”的按钮将具有“红色”前景。如果我删除 Application.Resources 中的全局样式,它就会起作用。我错过了什么吗?
应用程序.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>
主窗口.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>
最佳答案
隐式 TextBlock
定义于 App.xaml
不会被其他 TextBlock
覆盖样式。因此,建议您移动默认值 TextBlock
样式例如<Window.Resources>
.
有关这方面的更多信息,请参阅以下链接。
Implicit styles in Application.Resources vs Window.Resources?
覆盖 App.xaml 中的属性设置: https://social.msdn.microsoft.com/Forums/vstudio/en-US/f6822a5e-09c7-489b-b85d-833f1f9356dc/over-ride-the-property-setting-in-appxaml?forum=wpf
或者干脆不定义任何隐含的 TextBlock
风格。定义默认值 Style
每个Control
反而。
关于wpf - 覆盖应用程序广泛的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46240721/