简体   繁体   中英

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM