wpf - 覆盖应用程序广泛的样式

标签 wpf xaml app.xaml

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

在下面的示例中,当我希望它是“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/

相关文章:

c# - 如何关闭 silverlight 中的应用程序

wpf - 如何从代码隐藏中访问控件模板的元素

wpf - 如何使 WPF 文本框通过 ApplicationCommands?

wpf - 默认转换器何时启动?

c# - 文本未在 ListViewItem 中换行

.net - 如何从资源字典继承/扩展样式?

WPF - 颜色动画完成事件

c# - WPF xaml Visual Studio 不断自动更改到我的资源的路径

performance - 包含在 ScrollViewer 中的 LongListSelector 性能非常差

wpf - WPF 资源的范围 : Is pushing it to application scope (app. xaml) 对性能有好处吗?