You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在数据源对象状态变更时触发ListBoxItem的样式变化

实现方法

第一步:修改Human类实现属性变更通知

你需要先让Human类实现INotifyPropertyChanged接口,否则UI无法感知IsAnswered属性的变更,样式不会自动更新:

using System.ComponentModel;
using System.Runtime.CompilerServices;

public class Human : INotifyPropertyChanged
{
    private string _name;
    private bool _isAnswered;

    public string Name
    {
        get => _name;
        set
        {
            _name = value;
            OnPropertyChanged();
        }
    }

    public bool IsAnswered
    {
        get => _isAnswered;
        set
        {
            _isAnswered = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public override string ToString() => this.Name;
}

第二步:修改XAML添加样式触发

提供两种常用实现方案,按需选择即可:

方案1:基于现有ItemContainerStyle添加DataTrigger

改动手最小,无需修改原有ListBox的基础结构:

<ListBox ItemsSource="{Binding Humans}" DisplayMemberPath="Name">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <!-- 原有其他setter保留 -->
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsAnswered}" Value="True">
                    <Setter Property="FontWeight" Value="Bold"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

方案2:自定义ItemTemplate实现

灵活性更高,后续需要调整文本样式、添加其他展示元素时更易扩展,注意需要删除原有DisplayMemberPath属性,否则ItemTemplate不会生效:

<ListBox ItemsSource="{Binding Humans}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}">
                <TextBlock.Style>
                    <Style TargetType="TextBlock">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding IsAnswered}" Value="True">
                                <Setter Property="FontWeight" Value="Bold"/>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </TextBlock.Style>
            </TextBlock>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <!-- 原有其他setter保留 -->
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

内容的提问来源于stack exchange,提问作者z33k

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 02:18:03