您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

项目更改时通知ObservableCollection

项目更改时通知ObservableCollection

您注释为的位置// Code to trig on item change...仅在更改集合对象(例如将其设置为新对象或设置为null)时触发。

根据您目前的实现TrulyObservableCollection的,处理您的收藏的属性更改事件,注册一些东西到CollectionChanged的事件MyItemsSource

public Myviewmodel()
{
    MyItemsSource = new TrulyObservableCollection<MyType>();
    MyItemsSource.CollectionChanged += MyItemsSource_CollectionChanged;

    MyItemsSource.Add(new MyType() { MyProperty = false });
    MyItemsSource.Add(new MyType() { MyProperty = true});
    MyItemsSource.Add(new MyType() { MyProperty = false });
}


void MyItemsSource_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    // Handle here
}

我个人真的不喜欢这种实现。您正在引发一个CollectionChanged事件,该事件表明在属性更改时,整个集合已被重置。当然,只要集合中的某个项目发生更改,它就可以使UI随时更新,但是我发现这样做对性能不利,而且似乎没有办法确定更改了哪些属性,这是关键信息之一做某事时我通常需要PropertyChanged

我更喜欢使用常规方法ObservableCollection而只是将PropertyChanged事件关联到上的项目CollectionChanged。如果您的UI已正确绑定到中的项目,则ObservableCollection当集合中某个项目的属性发生更改时,您无需告诉UI进行更新。

public Myviewmodel()
{
    MyItemsSource = new ObservableCollection<MyType>();
    MyItemsSource.CollectionChanged += MyItemsSource_CollectionChanged;

    MyItemsSource.Add(new MyType() { MyProperty = false });
    MyItemsSource.Add(new MyType() { MyProperty = true});
    MyItemsSource.Add(new MyType() { MyProperty = false });
}

void MyItemsSource_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    if (e.NewItems != null)
        foreach(MyType item in e.NewItems)
            item.PropertyChanged += MyType_PropertyChanged;

    if (e.OldItems != null)
        foreach(MyType item in e.OldItems)
            item.PropertyChanged -= MyType_PropertyChanged;
}

void MyType_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName == "MyProperty")
        DoWork();
}
其他 2022/1/1 18:18:53 有484人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶