2017-09-15 48 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>