2017-09-15 49 views
1

我想为应用程序中的textblock定义全局样式,但我也希望能够覆盖此默认样式。我一直认为风格的局部重写比全球更重要,但似乎并非如此?覆盖应用程序宽样式

在下面的例子中,当我期望它是“Aqua”时,内容为“Test”的Button将具有“红色”前景。如果我删除Application.Resources中的全局样式,则会起作用。我错过了什么吗?

的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

<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> 

+0

,如果你希望能够覆盖它,不要在App.xaml中定义的隐含文本框的风格。 – mm8

回答

1

TextBlockApp.xaml定义不会被其他TextBlock风格来overrided。因此建议您将默认的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风格。改为为每个Control定义一个默认Style

0

您的问题是为TextBlock而不是Button定义您的应用程序级资源。大多数WPF控件使用TextBlocks作为默认方式来显示文本内容,所以通过尝试覆盖您的ButtonForeground,您正在执行此操作,但是它会再次被默认样式TextBlock覆盖。

改变你的App.xaml这个,你会得到你想要达到的效果:

<Application.Resources> 
    <Style TargetType="{x:Type Button}"> 
     <Setter Property="Foreground" Value="Red" /> 
    </Style> 
</Application.Resources>