views:

851

answers:

1

I can't figure out why this XAML code does not work. When using a TemplateBinding (see below), the background color is not set. But when I use a normal color string (i.e. "Red"), it works fine.

<ControlTemplate x:Key="InstanceButtonTemplate" TargetType="{x:Type Control}">
    <Grid>
        <Rectangle>
            <Rectangle.Fill>
                <SolidColorBrush Color="{TemplateBinding Background}"></SolidColorBrush>
            </Rectangle.Fill>
        </Rectangle>
    </Grid>
</ControlTemplate>

Yet, when I use a TemplateBinding in this way, it works Fine...

<ControlTemplate x:Key="InstanceButtonTemplate" TargetType="{x:Type Control}">
    <Grid>
        <Rectangle Fill="{TemplateBinding Background}"></Rectangle>
    </Grid>
</ControlTemplate>

Any ideas?

Edit: to clarify, I intend to expand this to rather use a gradient brush, that's why I need to be able to assign to the Rectangle.Fill property using XAML instead of a plain string.

+5  A: 

That is because Color has a different type then Background

Background is a Brush, Color is a.. well Color.. You can use a IValueConverter to convert your brush to a color..

HTH

Arcturus
That was my thought as well, but then I saw (using intellisense), Background (on Control) is actually a Brush, not a color.
willem
@willemo, that's exactly it though. Background is a Brush, and Rectangle.Fill is a brush. When you set SolidColorBrush.Color to the Background property, it fails because SolidColorBrush.Color is a Color, and Background is a Brush. Rectangle.Fill=Background is the way to go...both brushes.
Rich
Or write a nasty implementation of an IValueConverter which can convert brushes into colors... You do have to handle all different kind of brushes though.. more info on brushes here: http://msdn.microsoft.com/en-us/library/aa970904.aspx
Arcturus
Argh! Of course! Thank you, nicely spotted.
willem