列表框 DataTemplate 中 TextBlock 的条件格式 [英] Conditional formating of a TextBlock within a Listbox’s DataTemplate
问题描述
这是我的第一个 wcf &我遇到了一些看似基本的 XAML 概念的问题.
It’s my first wcf & I’m running into some trouble with what seems to be a basic XAML concept.
不知何故,PriorityStyle"中的数据触发器/绑定不起作用.我想这是因为上下文问题,但环顾四周,我没有设法找到答案.
Somehow the DataTrigger / Binding in the "PriorityStyle" is not working. I guess this is because of a context issue but looking around I haven’t manage to find the answers.
<UserControl … >
<UserControl.Resources>
<Style x:Key="PriorityStyle" TargetType="TextBlock" >
<Style.Triggers>
<DataTrigger Binding="{Binding Priority}" Value="High">
<Setter Property="Foreground" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
<DataTemplate x:Key="ItemTemplate">
<StackPanel Margin="3">
...
<DockPanel>
<TextBlock Name="Priority" Text="{Binding Priority}" Foreground ="#014f7c" Style="{StaticResource PriorityStyle}"/>
</DockPanel>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="SelectedTemplate">
...
</DataTemplate>
<Style TargetType="{x:Type ListBoxItem}" x:Key="ContainerStyle">
<Setter Property="ContentTemplate" Value="{StaticResource ItemTemplate}" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="ContentTemplate" Value="{StaticResource SelectedTemplate}" />
</Trigger>
<!-- DataBinding work in this Context, But in Style I cannot use a TargetName -->
<DataTrigger Binding="{Binding Priority}" Value="High">
<Setter Property="Background" Value="DarkOrange"/>
</DataTrigger>
</Style.Triggers>
</Style>
</UserControl.Resources>
<ListBox x:Name="ListBox" ItemContainerStyle="{StaticResource ContainerStyle}" />
推荐答案
as @HighCore 提到不确定您在何处设置 ListBox
的 Source,但前提是您的绑定在 的样式中有效>ListBoxItem
你可以试试变通办法
as @HighCore mentioned not sure where your setting the Source for your ListBox
, but provided your binding works in the Style for ListBoxItem
you can try a work-around
<Style x:Key="PriorityStyle" TargetType="TextBlock" >
<Setter Property="Foreground"
Value="Black" />
<Style.Triggers>
<DataTrigger Binding="{Binding DataContext.Priority, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}}" Value="High">
<Setter Property="Foreground" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
但您也将 Priority
属性绑定到 TextBlock
中的 Text
和 PriorityStyle
.所以你也可以这样做:
but your also binding Priority
property to Text
in the TextBlock
with PriorityStyle
anyways. So you could also just do:
<Style x:Key="PriorityStyle"
TargetType="TextBlock">
<Setter Property="Foreground"
Value="Black" />
<Style.Triggers>
<Trigger Property="Text"
Value="High">
<Setter Property="Foreground"
Value="Red" />
</Trigger>
</Style.Triggers>
</Style>
这样你甚至不需要遍历元素树的绑定
this way you don't even need a binding traversing through your element tree
这篇关于列表框 DataTemplate 中 TextBlock 的条件格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!