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

UWP中子属性变更时DependencyProperty更新问题

嘿,这个问题我之前也碰到过,其实核心原因是普通的List<string>不会主动通知UI集合内容的变化,再加上你的DependencyProperty默认只会检测对象引用的变更,不会深入监听子集合的内容更新。给你两个关键步骤来解决:

第一步:把List<string>换成ObservableCollection<string>

UWP里专门为数据绑定设计了ObservableCollection<T>,它自带INotifyCollectionChanged接口,当你添加、删除或者移动集合里的项时,会自动触发通知,让ListView实时刷新。

修改你的Test类:

public partial class Test : INotifyPropertyChanged
{
    private int _id;
    public int Id
    {
        get => _id;
        set
        {
            _id = value;
            OnPropertyChanged(nameof(Id));
        }
    }

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

    private ObservableCollection<string> _myList;
    public ObservableCollection<string> MyList
    {
        get => _myList;
        set
        {
            _myList = value;
            OnPropertyChanged(nameof(MyList));
        }
    }

    // 构造函数里初始化集合,避免空引用
    public Test()
    {
        MyList = new ObservableCollection<string>();
    }

    // 实现INotifyPropertyChanged,用于属性赋值时的通知
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

第二步:正确定义UserControl的DependencyProperty

确保你的DependencyProperty元数据设置正确,并且绑定路径能正确指向MyList:

在你的UserControl后台代码里定义DependencyProperty:

public sealed partial class YourUserControl : UserControl
{
    public static readonly DependencyProperty TestItemProperty =
        DependencyProperty.Register(
            "TestItem",
            typeof(Test),
            typeof(YourUserControl),
            new PropertyMetadata(null));

    public Test TestItem
    {
        get => (Test)GetValue(TestItemProperty);
        set => SetValue(TestItemProperty, value);
    }

    public YourUserControl()
    {
        this.InitializeComponent();
    }
}

然后在UserControl的XAML里绑定ListView的ItemsSource:

<ListView ItemsSource="{Binding TestItem.MyList, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:YourUserControl}}" />

为什么这样能解决问题?

  • ObservableCollection<string>在你调用Add()、Remove()等方法时,会自动触发CollectionChanged事件,ListView会监听这个事件来更新显示内容。
  • 给Test类实现INotifyPropertyChanged,如果以后你需要直接替换MyList的引用(比如testItem.MyList = new ObservableCollection<string>()),UI也能感知到这个属性的变化,及时更新绑定。

如果因为某些原因不能修改Test类里的集合类型,你也可以在绑定前把List<string>转换成ObservableCollection<string>,但这种方式不如直接用ObservableCollection来得省心。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:07:17