如何根据 DataTemplate 中的绑定值将相同的样式应用于一组控件?
我最近开始学习 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>
我想要做的是根据项目绑定值为 StackPanel 内的每个 TextBlock 设置 FontWeigth 属性。而不是在每个 TextBlock 上复制它。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能使用绑定表达式作为样式设置器值。您只能绑定到依赖项对象上的依赖项属性。
TextBlock 的各种字体属性继承自其父离子视觉树。您可以通过向用户控件添加多个 TextBlock 元素,然后在用户控件上设置 FontWeight 或 FontSize 属性来查看此操作。
因此,一种解决方案是在某些父元素上设置 FontWeight 并依赖继承。不幸的是,您无法在 StackPanel 上设置 FontWeight。我将插入一个 ContehtControl,如下所示:
这应该可行!
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:
This should work!