首页 > 解决方案 > 如何在底层对象状态更改时触发 ListBoxItem 的样式更改?

问题描述

我有一个 a 的基本设置,ListBoxItemSource属性设置为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. 如何做到这一点?

标签: wpftriggerslistboxstyleslistboxitem

解决方案


项目容器的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>

正如评论中已经指出的那样,您必须让Humanimplement INotifyPropertyChanged。该物业IsAnswered必须引发该INotifyPropertyChanged.PropertyChanged事件。否则不会传播属性的更改。


推荐阅读