chuckp
chuckp

Reputation: 313

WPF control styles - how to override a single setter value in a global control style ResourceDictionary file in a separate ResourceDictionary file

I declare the following ResourceDictionary, TargetType="TextBlock" in the App.xaml file:

    <ResourceDictionary>
        <Style TargetType="TextBlock">
            <Setter Property="Foreground" Value="Red"/>
            <Setter Property="FontStyle" Value="Italic"/>
            <Setter Property="FontSize" Value="20"/>
        </Style>
    </ResourceDictionary>

Later, after the application has started, I want to be able to on-demand load another resource file (MyCustomResources.xaml) that has a style declaration, again with TargetType="TextBlock", but with ONLY one Setter that declares a Forground color of "Green". The "Green" Foreground color will need to globally override the original Foreground "Red".

<ResourceDictionary>
    <Style TargetType="TextBlock">
        <Setter Property="Foreground" Value="Green"/>
    </Style>
</ResourceDictionary>

For this application, overriding the Foreground color for a TextBlock in a local view xaml file is not acceptable.

I want to still keep and use the other two global Setter properties for FontStyle and FontSize for TextBlock controls declared in the App.xaml file, without having to declare them again in the MyCustomResources.xaml file.

Is it possible to do what I am describing here, or some other way?

Upvotes: 0

Views: 694

Answers (1)

the.Doc
the.Doc

Reputation: 886

If you use merged dictionaries, I believe the order they are added to the collection is used to determine precedence.

So if you're app.xaml is defined as so:

<Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/DefaultDict.xaml" />
                <ResourceDictionary Source="/Override.xaml" />
            </ResourceDictionary.MergedDictionaries>    
            <Style TargetType="TextBlock" x:Key="baseStyle">
                <Setter Property="Foreground" Value="White" />
                <Setter Property="FontSize" Value="20" />
            </Style>
        </ResourceDictionary>
 </Application.Resources>

Then in DefaultDict.xaml you simply create an implicit style which all textblocks will use until the override file is loaded.

<Style TargetType="TextBlock" BasedOn="{StaticResource baseStyle}">            
</Style>

And your Override.xaml you can override any setters.

<Style TargetType="TextBlock" BasedOn="{StaticResource baseStyle}">
    <Setter Property="Foreground" Value="Pink" />
</Style>

You should be able to add and remove your override file at runtime and it should update correctly

Upvotes: 1

Related Questions