wpf - 如何在底层对象状态更改时触发 ListBoxItem 的样式更改?
问题描述
我有一个 a 的基本设置,ListBox
其ItemSource
属性设置为ObservableCollection<Human>
.
<ListBox ItemsSource="{Humans}" DisplayMemberPath="Name">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<!-- Some setters -->
</Style>
</ListBox>
Human
定义如下:
public class Human
{
public string Name { get; set; }
public bool IsAnswered { get; set; }
public override string ToString() => this.Name;
}
因此,我们有一个Human
对象作为列表框的每个项目的源,并显示其字符串表示形式(Name
在本例中为属性)的默认行为。
现在,我希望显示的Human.Name
值在IsAnswered
更改为true
. 如何做到这一点?
解决方案
项目容器的DataContext
始终是数据模型,在您的情况下是Human
实例。因此只需绑定到DataContext
:
<ListBox>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Style.Triggers>
<DataTrigger Binding="{Binding IsAnswered}" Value="True">
<Setter Property="FontWeight" Value="Bold" />
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
正如评论中已经指出的那样,您必须让Human
implement INotifyPropertyChanged
。该物业IsAnswered
必须引发该INotifyPropertyChanged.PropertyChanged
事件。否则不会传播属性的更改。
推荐阅读
- c - C 语言语法: if { ... } while(0);
- java - Android Studio 在 adView.loadAd(adRequest) 错误时出现空指针异常错误。并在安卓棒棒糖设备上崩溃
- entity-framework - 实体框架最大 ID
- javascript - 使用 Ajax 响应在浏览器中显示 FPDF
- java - 为什么 java 参数在 Windows 和 Linux 中的行为不同?
- asp.net-mvc-5 - 使用 OpenIDConnect 进行 Azure AD 身份验证后无法解决无限循环问题 - 授权码授予
- java - 如何知道是否使用 log4j 正确发送了 syslog 消息而不依赖于异常
- c# - 有什么办法可以隐藏铬硒?
- c# - CS0246: 找不到类型或命名空间名称“系统”
- java - 无法使用 ArrayList 初始化 ArrayAdaper:Java