C# WPF - 集合中的属性的 OnPropertyChanged
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/956165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF - OnPropertyChanged for a property within a collection
提问by Adam Barney
In a view model, I have a collection of items of type "ClassA" called "MyCollection". ClassA has a property named "IsEnabled".
在视图模型中,我有一个名为“MyCollection”的“ClassA”类型的项目集合。ClassA 有一个名为“IsEnabled”的属性。
class MyViewModel
{
List<ClassA> MyCollection { get; set; }
class ClassA { public bool IsEnabled { get; set; } }
}
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.
我的视图有一个绑定到 MyCollection 的数据网格。每行都有一个按钮,其“IsEnabled”属性绑定到 ClassA 的 IsEnabled 属性。
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:
当视图模型中的条件发生变化,以至于需要禁用 MyColllction 列表中的一项特定项时,我将 IsEnabled 属性设置为 false:
MyCollection[2].IsEnabled = false;
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 事件通知 View 此更改,但我不知道如何引用集合中的特定项目。
OnPropertyChanged("MyCollection");
OnPropertyChanged("MyCollection[2].IsEnabled");
both do not work.
两者都不起作用。
How do I notify the View of this change? Thanks!
我如何通知视图此更改?谢谢!
采纳答案by Thomas Levesque
ClassA needs to implement INotifyPropertyChanged :
ClassA 需要实现 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));
}
}
EDIT: and use an ObservableCollection like Scott said
编辑:并使用像 Scott 所说的 ObservableCollection
EDIT2: made invoking PropertyChanged event shorter
EDIT2:缩短了调用 PropertyChanged 事件的时间
回答by Scott Whitlock
Instead of using a List, try using an ObservableCollection. Also, modify your ClassA so that it implements INotifyPropertyChanged, particularly for the IsEnabled property. Finally, modify your MyViewModel class so it also implements INotifyPropertyChanged, especially for the MyCollection property.
不要使用 List,而是尝试使用 ObservableCollection。此外,修改您的 ClassA,使其实现 INotifyPropertyChanged,特别是对于 IsEnabled 属性。最后,修改您的 MyViewModel 类,使其也实现 INotifyPropertyChanged,尤其是对于 MyCollection 属性。