WPF - 集合中的属性的 OnPropertyChanged [英] WPF - OnPropertyChanged for a property within a collection

查看:24
本文介绍了WPF - 集合中的属性的 OnPropertyChanged的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在视图模型中,我有一个名为MyCollection"的ClassA"类型的项目集合.ClassA 有一个名为IsEnabled"的属性.

In a view model, I have a collection of items of type "ClassA" called "MyCollection". ClassA has a property named "IsEnabled".

class MyViewModel 
{
    List<ClassA> MyCollection { get; set; }

    class ClassA { public bool IsEnabled { get; set; } }
}

我的视图有一个绑定到 MyCollection 的数据网格.每行都有一个按钮,其IsEnabled"属性绑定到 ClassA 的 IsEnabled 属性.

My view has a datagrid which binds to MyCollection. Each row has a button whose "IsEnabled" attribute is bound to the IsEnabled property of ClassA.

当视图模型中的条件发生变化,以至于需要禁用 MyColllction 列表中的一个特定项时,我将 IsEnabled 属性设置为 false:

When conditions in the view model change such that one particular item in the MyCollction list needs to bow be disabled, I set the IsEnabled property to false:

MyCollection[2].IsEnabled = false;

我现在想用 OnPropertyChanged 事件通知 View 此更改,但我不知道如何引用集合中的特定项目.

I now want to notify the View of this change with a OnPropertyChanged event, but I don't know how to reference a particular item in the collection.

OnPropertyChanged("MyCollection");
OnPropertyChanged("MyCollection[2].IsEnabled");

两者都不起作用.

我如何通知视图此更改?谢谢!

How do I notify the View of this change? Thanks!

推荐答案

ClassA 需要实现 INotifyPropertyChanged :

ClassA needs to implement INotifyPropertyChanged :

class ClassA : INotifyPropertyChanged
{
    private bool _isEnabled;
    public bool IsEnabled
    {
        get { return _isEnabled; }
        set
        {
            if (value != _isEnabled)
            {
                _isEnabled = value;
                OnPropertyChanged("IsEnabled");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

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

并使用像 Scott 所说的 ObservableCollection

and use an ObservableCollection like Scott said

缩短了调用 PropertyChanged 事件的时间

made invoking PropertyChanged event shorter

这篇关于WPF - 集合中的属性的 OnPropertyChanged的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆