Sunday, May 17, 2009

TemplateBinding in Silverlight

A week ago, or two, on silverlight forums there was a question regarding the TemplateBinding of background property to foreground. The question was:
Can I bind background property to foreground property? I tried this but it didn't work:

<ControlTemplate Key="btnTemplate" TargetType="Button">
<Rectangle>
<Rectangle.Fill>

<SolidColorBrush Color="TemplateBinding Background.Brush">
</SolidColorBrush>

</Rectangle.Fill>

</Rectangle>
</ControlTemplate>

The Red Color code is the main problem. We can bind properties of same Type regardless of their name. The problem here is that, the type of Background is Brush while the programmer is specifying a concrete class SolidColorBrush. Background is not necessarily of type SolidColorBrush. It can be RadialGradientBrush, VideoBrush, DrawingBrush etc. Here is the right code:

<ControlTemplate Key="btnTemplate" TargetType="Button">
<Rectangle Fill="{TemplateBinding Background}" />
</ControlTemplate>

Moral:
Don't try to restrict your options to only SolidColorBrush if it provides you with the richness of other Brush(es), also.

No comments:

Post a Comment