1

我对 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 属性的变化。我怎么做?

提前感谢您的帮助。

4

2 回答 2

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>implements类型INotifyCollectionChanged,那么您必须监视集合更改以分别订阅/取消订阅PropertyChanged新/旧项目的事件。

于 2012-09-04T18:17:48.223 回答
0

当您分配一个新的 SupplierSelect 时,将一个处理程序添加到 CustomerSupplier 中的 SupplierSelect 的 PropertyChanged 事件。

于 2012-09-04T18:16:05.597 回答