Alex Burtsev
Alex Burtsev

Reputation: 12668

How to apply same style to a group of controls based on binding value inside DataTemplate?

I have recently started learning Silverlight and can't figure out how make this work.

<ComboBox.ItemTemplate>
    <DataTemplate>
        <StackPanel Orientation="Horizontal">
            <StackPanel.Resources>
                <Style TargetType="TextBlock">
                    <Setter Property="FontWeight" Value="{Binding Path=FontWeight}"/>
                </Style>
            </StackPanel.Resources>
            <TextBlock Text="{Binding Path=Name}" Margin="0,0,5,0"/>
            <TextBlock  Text="{Binding Path=Prefix}"/>
        </StackPanel>
    </DataTemplate>
</ComboBox.ItemTemplate>

What i want to do is set FontWeigth property for each TextBlock inside StackPanel based on item binding value. Instead of duplicating it on every TextBlock.

Upvotes: 1

Views: 207

Answers (1)

ColinE
ColinE

Reputation: 70142

You cannot use binding expressions as style setter values. You can only bind to dependency properties on dependency objects.

The various font properties of TextBlock are inherited from its parent ion the visual tree. You can see this in action by adding a number of TextBlock elements to a Usercontrol, then setting the FontWeight or FontSize property on the Usercontrol.

So, one solution is to set the FontWeight on some parent element and rely on inheritence. Unfortunately you cannot set FontWeight on your StackPanel. I would insert a ContehtControl that as follows:

<ComboBox.ItemTemplate>
    <DataTemplate>
        <ContentControl FontWeight="{Binding Path=FontWeight}">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Path=Name}" Margin="0,0,5,0"/>
                <TextBlock  Text="{Binding Path=Prefix}"/>
            </StackPanel>
        </ContentControl>
    </DataTemplate>
</ComboBox.ItemTemplate>

This should work!

Upvotes: 1

Related Questions