c# - 处理属性(property)变更事件

标签 c# wpf mvvm

我对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的属性来处理关系。我需要从客户 View 模型内部检测类SupplierSelect的Selected属性的更改。我怎么做?

在此先感谢您的帮助。

最佳答案

像这样:

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事件。

关于c# - 处理属性(property)变更事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12269109/

相关文章:

c# - 使用 LINQ 在 C# 中获取 List<> 元素位置

c# - 数据绑定(bind)到 EF 实体或 ViewModel

wpf - MVVM 设计 - 处理多个 View 的通用 ViewModel

c# - WPF 中的 Windows 小工具 - 在激活 "Show desktop"时显示

wpf - 在WPF Blend的逻辑树中设置DataContext

c# - 使用ftp协议(protocol)下载大文件

c# - 这个用于属性初始化的 C# 模式是什么?

c# - 使用嵌套的 LambdaExpressions 编译 LambdaExpression 时,它们也会编译吗?

c# - 通过 View 模型构造函数传递的对象实例的理想数量(依赖注入(inject))

wpf - 如何使用 IDataErrorInfo 实现条件验证