Search code examples
xamlwinrt-xamlresourcedictionarystaticresource

How to override ResourceDictionary values


I have a resource dictionary like this:

<ResourceDictionary>
    <SolidColorBrush x:Key="SpecialColor" Color="Yellow" />
    <DataTemplate x:Key="SpecialTemplate">
        <Rectangle Fill="{StaticResource SpecialColor}" />
    </DataTemplate>
</ResourceDictionary>

I add my resource dictionary to my page like this:

<Page.Resources>
    <ResourceDictionary Source="ms-appx:///Style/Special.xaml" />
</Page.Resources>

I use the SpecialRectangle like this:

<ContentPresenter ContentTemplate="{StaticResource SpecialTemplate}" />

Question: How do I change the color?

[update] I tried this, but it did not work for me:

<Page.Resources>
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="ms-appx:///Style/Special.xaml" />
    </ResourceDictionary.MergedDictionaries>
    <SolidColorBrush x:Key="SpecialColor" Color="Red" />
</Page.Resources>

This also did not work:

<Page.Resources>
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="ms-appx:///Style/Special.xaml" />
        <ResourceDictionary>
            <SolidColorBrush x:Key="SpecialColor" Color="Red" />
        </ResourceDictionary>
    </ResourceDictionary.MergedDictionaries>
</Page.Resources>

Thanks.


Solution

  • You have many options depending on conditions - mainly

    1. Change color based on what?
    2. Where is the ContentPresenter and if perf is more important or developer convenience/clear architecture is.

    You can use template selector and use two templates instead of one, you can bind the Fill of the rectangle, you could use a VisualStateManager, you could use the CCC event if you're in a ListView and want to have best possible performance with no bindings, you could also simply walk the visual tree and annoy a few people. :)