Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silverlight: How to use a binding in setter for a style (or an equivalent work around)

If the person who answered this question is right, you cannot put a binding as the value in a setter in a style in Silverlight. Which is a shame, because I have 4 textblocks that all use the exact same binding for their Opacity property. Is there anyway to in a sense "style" their Opacity property so that all four of them point to the same binding? Otherwise, I have to set each Opacity property individually. In my case it's even worse - all four share other property bindings as well, which means each TextBlock declaration is pretty dang long, and yet they're all virtually the same (their property bindings, that is). I know I could concisely set all their shared property bindings in the code-behind, but I'd like a XAML solution if there is one.

Thanks!

like image 305
JoeCool Avatar asked Feb 02 '11 18:02

JoeCool


2 Answers

Here is how its done. You use a ContentControl and specify a ControlTemplate for it as a static resource:-

<Grid.Resources>
    <ControlTemplate x:Key="CommonTextBlock" TargetType="ContentControl">
        <TextBlock Opacity="{Binding SomeOpacity}" Text="{TemplateBinding Content}" />
    </ControlTemplate>
<Grid.Resource>
<ContentControl Content="{Binding SomeTextValue}" Template="{StaticResource CommonTextBlock}" />
<ContentControl Content="{Binding SomeOtherTextValue}" Template="{StaticResource CommonTextBlock}" />

Now you can bung as may other properties with bindings in to the Control Template as you want.

This approach could be extended to Style:-

<Grid.Resources>
    <ControlTemplate x:Key="CommonTextBlock" TargetType="ContentControl">
        <TextBlock Opacity="{Binding SomeOpacity}" Text="{TemplateBinding Content}" />
    </ControlTemplate>
    <Style x:Key="CommonTextBlockStyle" TargetType="ContentControl">
       <Setter Property="Template" Value="{StaticResource CommonTextBlock}" />
       <Setter Property="Foreground" Value="Blue" />
    </Style>
<Grid.Resource>
<ContentControl Content="{Binding SomeTextValue}" Style="{StaticResource CommonTextBlockStyle}" />
<ContentControl Content="{Binding SomeOtherTextValue}" Style="{StaticResource CommonTextBlockStyle}" />
like image 154
AnthonyWJones Avatar answered Jan 21 '23 10:01

AnthonyWJones


Check out SetterValueBindingHelper in this blog article and support for Binding in style setters is announced for SL5.

like image 39
Denis Avatar answered Jan 21 '23 11:01

Denis