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

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

问题描述

在一个视图模型,我有型ClassA的的项目名为MyCollection的的集合。 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; } }
}

我的观点有一个DataGrid结合到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.

当在这样的MyCollction列表中的一个特定项目需要低头查看模式变革的条件被禁用,我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事件的视图,但我不知道如何引用集合中的特定项目。

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");

这两个不工作。

both do not work.

我怎么通知这种变化的景观?谢谢!

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)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

编辑:和使用一个ObservableCollection像斯科特说

and use an ObservableCollection like Scott said

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

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