我对C#中的财产变更处理存有疑问。我的场景如下:我有两个班级
public class CustomerSupplier : ViewModelBase
{
public Customer Customer { get; set; }
private IEnumerable<SupplierSelect> suppliersSelect;
public IEnumerable<SupplierSelect> SuppliersSelect
{
get
{
return suppliersSelect;
}
set
{
suppliersSelect = value;
this.NotifyPropertyChanged("SuppliersSelect");
}
}
}
public class SupplierSelect : ViewModelBase
{
public Supplier Supplier { get; set; }
private bool selected;
public bool Selected
{
get
{
return selected;
}
set
{
selected = value;
this.NotifyPropertyChanged("Selected");
}
}
}
ViewModelBase以通常的方式实现NotifyPropertyChanged。在我的CustomersViewModel中,我有一个CustomerSupplier类型的属性来处理关系。我需要的是从CustomersViewModel内部检测到SupplierSelect类的Selected属性的更改。我该怎么做?
提前感谢您的帮助。
答案 0 :(得分:1)
这样的事情:
public class CustomerSupplier : ViewModelBase
{
public Customer Customer { get; set; }
private void HandleSupplierSelectPropertChanged(object sender, PropertyChangedEventArgs args)
{
if (args.PropertyName == "Selected")
{
var selectedSupplier = (SupplierSelect)sender;
// ...
}
}
private IEnumerable<SupplierSelect> suppliersSelect;
public IEnumerable<SupplierSelect> SuppliersSelect
{
get
{
return suppliersSelect;
}
set
{
if (suppliersSelect != value)
{
if (suppliersSelect != null)
{
foreach (var item in suppliersSelect)
item.PropertyChanged -= HandleSupplierSelectPropertChanged;
}
suppliersSelect = value;
if (suppliersSelect != null)
{
foreach (var item in suppliersSelect)
item.PropertyChanged += HandleSupplierSelectPropertChanged;
}
this.NotifyPropertyChanged("SuppliersSelect");
}
}
}
}
另请注意:如果IEnumerable<SupplierSelect>
的实际类型实现了INotifyCollectionChanged
,那么您必须监视集合更改,以分别为新/旧项目订阅/取消订阅PropertyChanged
事件。
答案 1 :(得分:0)
当您分配新的SupplierSelect时,会在CustomerSupplier中为SupplierSelect的PropertyChanged事件添加处理程序。