Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding application wide style

Tags:

wpf

xaml

app.xaml

I want to define a global style for textblock in the application but I also want to be able to override this default style. I always thought that the local override of style has more priority than the global one but it doesn't seems to be the case?

In the following example, the Button with content "Test" will have a "Red" foreground when I expect it to be "Aqua". If I remove the global style in Application.Resources, than it will works. Did I'm missing something?

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>

like image 540
Melursus Avatar asked Oct 18 '25 18:10

Melursus


1 Answers

Implicit TextBlock defined in App.xaml will not be overrided by other TextBlock styles. It's therefore recommended that you move your default TextBlock style to for example <Window.Resources>.

Please refer to the following links for more information about this.

Implicit styles in Application.Resources vs Window.Resources?

Over ride the Property setting in 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

Or simply don't define any implicit TextBlock style. Define a default Style for each Control instead.

like image 154
mm8 Avatar answered Oct 22 '25 05:10

mm8