简体   繁体   English

如何基于DataTemplate内部的绑定值将相同样式应用于一组控件?

[英]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. 我最近开始学习Silverlight,不知道如何使它起作用。

<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. 我要根据项目绑定值为StackPanel中的每个TextBlock设置FontWeigth属性。 Instead of duplicating it on every TextBlock. 而不是在每个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. TextBlock的各种字体属性是从其父树可视化树继承的。 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. 通过将多个TextBlock元素添加到Usercontrol,然后在Usercontrol上设置FontWeight或FontSize属性,可以看到实际的效果。

So, one solution is to set the FontWeight on some parent element and rely on inheritence. 因此,一种解决方案是在某些父元素上设置FontWeight并依靠继承。 Unfortunately you cannot set FontWeight on your StackPanel. 不幸的是,您不能在StackPanel上设置FontWeight。 I would insert a ContehtControl that as follows: 我将插入一个ContehtControl,如下所示:

<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! 这应该工作!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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