JoeyWang
JoeyWang

Reputation: 1

How to override SolidColorBrush resource defined in a Style?

How to cover SolidColorBrush out of ResourceDictionary in WPF?

ButtonStyle1.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:PresentationOptions="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <SolidColorBrush x:Key="ButtonBackgroundColor" Color="LightGreen" PresentationOptions:Freeze="true" />
    
    <Style TargetType="Button">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <TextBlock Background="{StaticResource ButtonBackgroundColor}">Hello World</TextBlock>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>    
</ResourceDictionary>

ButtonWindow.xaml

<Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>                
                <ResourceDictionary Source="ButtonStyle1.xaml" />
            </ResourceDictionary.MergedDictionaries>
            <SolidColorBrush x:Key="ButtonBackgroundColor" Color="LightSkyBlue"/>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <Button Content="Button" HorizontalAlignment="Left" Margin="275,140,0,0" VerticalAlignment="Top" Height="68" Width="159"/>

    </Grid>

I want to cover the color with LightSkyBlue, but it failed. How can do it? Thanks.

Upvotes: 0

Views: 67

Answers (1)

Dragan Radovac
Dragan Radovac

Reputation: 11

This piqued my curiosity so my implementation uses the suggestion of Sinus32(in the comments) to replace StaticResouce with DynamicResource in the Button ControlTemplate. It worked.

ButtonStyle1.xaml

<SolidColorBrush x:Key="ButtonBackgroundColor" Color="LightGreen" PresentationOptions:Freeze="true" />

<Style TargetType="Button">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate>
                <TextBlock Background="{DynamicResource ButtonBackgroundColor}">Hello World</TextBlock>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>  

ButtonWindow.xaml

<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="ButtonStyle1.xaml" />
        </ResourceDictionary.MergedDictionaries>
        <SolidColorBrush x:Key="ButtonBackgroundColor" Color="LightSkyBlue"/>
    </ResourceDictionary>
</Window.Resources>
<Grid>
    <Button Content="Button" HorizontalAlignment="Left" Margin="275,140,0,0" VerticalAlignment="Top" Height="68" Width="159"/>
</Grid>

enter image description here

Upvotes: 0

Related Questions