How to assign WPF resources to other resource tags

Posted by Tom on Stack Overflow See other posts from Stack Overflow or by Tom
Published on 2010-06-14T10:46:36Z Indexed on 2010/06/14 10:52 UTC
Read the original article Hit count: 215

Filed under:
|
|
|

This is quite obscure, I may just be missing something extremely simple.

Scenario 1

Lets say I create a gradient brush, like this in my <Window.Resources> section:

<LinearGradientBrush x:Key="GridRowSelectedBackBrushGradient" StartPoint="0,0" EndPoint="0,1">
    <GradientStop Color="#404040" Offset="0.0" />
    <GradientStop Color="#404040" Offset="0.5" />
    <GradientStop Color="#000000" Offset="0.6" />
    <GradientStop Color="#000000" Offset="1.0" />
</LinearGradientBrush>

Then much later on, I want to override the HighlightBrushKey for a DataGrid. I have basically done it like this (horrible);

<LinearGradientBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
                     GradientStops="{Binding Source={StaticResource GridRowSelectedBackBrushGradient}, Path=GradientStops}"
                     StartPoint="{Binding Source={StaticResource GridRowSelectedBackBrushGradient}, Path=StartPoint}"
                     EndPoint="{Binding Source={StaticResource GridRowSelectedBackBrushGradient}, Path=EndPoint}" />

This is obviously not the most slick way of referencing a resource. I also came up with the following problem, which is almost identical.

Scenario 2

Say I created two colors in my <Window.Resources> markup, like so:

<SolidColorBrush x:Key="DataGridRowBackgroundBrush" Color="#EAF2FB" />
<SolidColorBrush x:Key="DataGridRowBackgroundAltBrush" Color="#FFFFFF" />

Then later on, I want to supply them in an Array, which feeds the ConverterParameter on a Binding so I can supply the custom Converter with my static resource instances:

<Setter Property="Background">
    <Setter.Value>
        <Binding RelativeSource="{RelativeSource Mode=Self}" 
                 Converter="{StaticResource BackgroundBrushConverter}">
            <Binding.ConverterParameter>
                <x:Array Type="{x:Type Brush}">
                    <SolidColorBrush Color="{Binding Source={StaticResource DataGridRowBackgroundBrush}, Path=Color}" />
                    <SolidColorBrush Color="{Binding Source={StaticResource DataGridRowBackgroundAltBrush}, Path=Color}" />
                </x:Array>
            </Binding.ConverterParameter>
        </Binding>
    </Setter.Value>
</Setter>

What I've done is attempt to rereference an existing resource, but in my efforts I've actually recreated the resource, and bound the properties so they match. Again, this is not ideal.

Because I've now hit this problem at least twice, is there a better way?

Thanks, Tom

© Stack Overflow or respective owner

Related posts about .NET

Related posts about wpf