【发布时间】:2017-08-22 13:31:55
【问题描述】:
我已搜索但尚未找到任何方法来执行此操作。我对 XAML 和绑定也比较陌生。
我有很多TextBlocks,其中的文本绑定到一个属性并且有一个StringFormat:
<TextBlock Text="{Binding PropA, StringFormat=Running {0}"/>
<TextBlock Text="{Binding Height, StringFormat=Sub: \{0\}"/>
<TextBlock Text="{Binding Depth, StringFormat=Indie: \{0\}"/>
<TextBlock Text="{Binding Color, StringFormat=State: \{0\}"/>
现在我想根据绑定变量的值应用样式(因此显示的真实文本无关紧要)。目前我必须对每个元素应用 <Style> 并再次直接使用绑定属性。这看起来很麻烦并且容易出现复制粘贴错误。我想知道我是否可以定义一个<Style> 并分享它。
类似:
<Style x:Key="Highlight_Non_Zero">
<!-- invert the logic because DataTrigger is an equality comparer -->
<Setter Property="TextBlock.Background" Value="Orange"/>
<Style.Triggers>
<DataTrigger Binding="{Binding <some magic here that gets the element this style applies to bound variable>" Value="0">
<Setter Property"TextBlock.Background" Value="Transparent"/>
</DataTrigger>
</Style.Triggers>
</Style>
<TextBlock Text="{Binding PropA, StringFormat=Running {0}" Style="{StaticResource Highlight_Non_Zero}"/>
<TextBlock Text="{Binding Height, StringFormat=Sub: \{0\}" Style="{StaticResource Highlight_Non_Zero}"/>
<TextBlock Text="{Binding Depth, StringFormat=Indie: \{0\}" Style="{StaticResource Highlight_Non_Zero}"/>
<TextBlock Text="{Binding Color, StringFormat=State: \{0\}" Style="{StaticResource Highlight_Non_Zero}"/>
【问题讨论】:
标签: c# xaml data-binding