【问题标题】:Overriding application wide style覆盖应用程序范围的样式
【发布时间】:2018-02-24 17:08:05
【问题描述】:

我想在应用程序中为文本块定义一个全局样式,但我也希望能够覆盖这个默认样式。我一直认为样式的本地覆盖比全局的优先级更高,但似乎并非如此?

在以下示例中,内容为“Test”的 Button 将具有“Red”前景,而我预计它是“Aqua”。如果我删除 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>

【问题讨论】:

  • 如果您希望能够覆盖它,请不要在 App.xaml 中定义您的隐式 TextBox 样式。

标签: wpf xaml app.xaml


【解决方案1】:

App.xaml 中定义的隐式TextBlock 不会被其他TextBlock 样式覆盖。因此,建议您将默认的TextBlock 样式移动到例如&lt;Window.Resources&gt;

有关更多信息,请参阅以下链接。

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

【讨论】:

    【解决方案2】:

    您的问题在于为TextBlock 而不是Button 定义应用程序级资源。大多数 WPF 控件使用 TextBlocks 作为默认显示文本内容的方式,因此通过尝试覆盖您的 Button Foreground,您正在这样做,但随后它又被 TextBlock 默认样式覆盖。

    将您的 App.xaml 更改为此,您将获得您想要实现的结果:

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

    【讨论】:

      猜你喜欢
      • 2012-03-04
      • 2019-06-10
      • 2020-09-12
      • 2011-11-23
      • 1970-01-01
      • 2018-10-14
      • 1970-01-01
      • 1970-01-01
      • 2020-01-04
      相关资源
      最近更新 更多