views:

152

answers:

2

I have a DataTemplate and a SolidColorBrush in the DataTemplate.Resources section. I want to bind the color to a property of the same data object that the DataTemplate itself is bound to. However, this does not work. The brush is ignored. Why?

Here is the simplified code:

        <DataTemplate DataType="{x:Type data:MyData}" x:Name="dtData">
            <DataTemplate.Resources>
                <SolidColorBrush x:Key="bg" Color="{Binding Path=Color, Converter={StaticResource colorConverter}" />
            </DataTemplate.Resources>
            <Border CornerRadius="15"
                    Background="{StaticResource bg}"
                    Margin="0"
                    Opacity="0.5"
                    Focusable="True">
        </DataTemplate>

I understand I could set this directly also but I need the color to be a resource.

+1  A: 

"Works on My Machine" :) I have one theory. You binding is working, you border has no content so it's only consist of a border itself, but you setting background property not the BorderBrush, so actualy you background has no area, also you don't set BorderThickness so actually you have border with 0 width and 0 height. So set BorderThickness, Width or Height.

Andrew
+1  A: 

Alternatively, you can simplify with below.

    <DataTemplate DataType="{x:Type data:MyData}" x:Name="dtData">
        <Border CornerRadius="15"
                Background="{Binding Path=Color, Converter={StaticResource colorConverter}}"
                Margin="0"
                Opacity="0.5"
                Focusable="True">
    </DataTemplate>
Jerry Liu
I understand this is simpler, but as I commented above I have to set the background color's opacity. AFAIK the opacity can only be set there without affecting the opacity of the entire Border (meaning elements inside it)!
John