[原创]
我有一个ListBox
它ItemsSource
(这是在创建窗口时在后面的代码中完成的)数据绑定到一个ObservableCollection
. 然后针对这些项目分配ListBox
了以下内容:DataTemplate
用户控件.xaml
<ListBox x:Name="communicatorListPhoneControls"
ItemContainerStyle="{StaticResource templateForCalls}"/>
应用程序.xaml
<Style x:Key="templateForCalls" TargetType="{x:Type ListBoxItem}">
<Setter Property="ContentTemplate" Value="{StaticResource templateRinging}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=hasBeenAnswered}" Value="True">
<Setter Property="ContentTemplate" Value="{StaticResource templateAnswered}"/>
</DataTrigger>
</Style.Triggers>
</Setter>
</Style>
当ObservableCollection
使用对象更新 时,这会出现在ListBox
具有正确初始值DataTemplate
的 中,但是当hasBeenAnswered
属性设置为true
(调试时我可以看到集合是正确的)时,DataTrigger
不会重新评估然后更新ListBox
以使用正确的DataTemplate
.
我已经INotifyPropertyChanged
在我的对象中实现了事件,如果在模板中绑定了一个值,我可以看到值更新。只是DataTrigger
不会重新评估并更改为正确的模板。
我知道DataTrigger
绑定是正确的,因为如果我关闭窗口并再次打开它,它将正确应用第二个数据模板,因为hasBeenAnswered
设置为true
.
[编辑 1]
根据 Timores 的评论,我尝试了以下方法:
用户控件.xaml
<ListBox x:Name="communicatorListPhoneControls"
ItemTemplate="{StaticResource communicatorCallTemplate}"/>`
应用程序.xaml:
<DataTemplate x:Key="communicatorCallTemplate">
<Label x:Name="test">Not answered</Label>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=hasBeenAnswered}" Value="True">
<Setter TargetName="test" Property="Background" Value="Blue"/>
</DataTrigger>
</DataTemplate.Triggers>
</Label>
</DataTemplate>
现在发生的情况与第一个示例类似,当“未接听”标签显示来电时(每个呼叫存在一个,因为这是一个列表框 - 通常当窗口加载时不会有呼叫),然后呼叫已回答并且属性hasBeenAnswered
设置为 true,但“未回答”保持不变。如果我关闭窗口,然后再次重新打开它(活动调用仍将属性 hasBeenAnswered 设置为 true),则背景为蓝色。所以在我看来,数据触发器根本没有运行,直到窗口重新运行。