【发布时间】:2023-03-31 23:55:02
【问题描述】:
[原创]
我有一个ListBox,它的ItemsSource(这是在创建窗口时在后面的代码中完成的)数据绑定到ObservableCollection。然后ListBox 会针对这些项目分配以下DataTemplate:
用户控件.xaml
<ListBox x:Name="communicatorListPhoneControls"
ItemContainerStyle="{StaticResource templateForCalls}"/>
app.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 制造的 cmets 之后,我尝试了以下方法:
用户控件.xaml
<ListBox x:Name="communicatorListPhoneControls"
ItemTemplate="{StaticResource communicatorCallTemplate}"/>`
app.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),则背景为蓝色。所以在我看来,数据触发器根本没有运行,直到窗口重新运行。
【问题讨论】:
标签: wpf datatemplate datatrigger