user1620696
user1620696

Reputation: 11375

Handling Property Change Event

I have a doubt about property change handling in C#. My scenario is as follows: I have two classes

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");
        }
    }
}

Where the ViewModelBase just implements the NotifyPropertyChanged in the usual way. In my CustomersViewModel I have a property of type CustomerSupplier to handle the relatonships. What I need is to detected the change in the Selected property of the class SupplierSelect from inside the CustomersViewModel. How do I do that?

Thanks in advance for the aid.

Upvotes: 1

Views: 1862

Answers (2)

Dennis
Dennis

Reputation: 37760

Something like this:

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");
            }
        }
    }
}

Also note: if the real type of IEnumerable<SupplierSelect> implements INotifyCollectionChanged, then you have to monitor collection changes to subscribe/unsubscribe to a PropertyChanged event for a new/old items respectively.

Upvotes: 1

Yoztastic
Yoztastic

Reputation: 862

When you assign a new SupplierSelect add a handler to the SupplierSelect's PropertyChanged event in the CustomerSupplier.

Upvotes: 0

Related Questions