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