How To Raise Property Changed events on a Dependency Property?

Muad'Dib picture Muad'Dib · Mar 19, 2010 · Viewed 123.3k times · Source

I have a control with two properties. One is a DependencyProperty, the other is an "alias" to the first one. How do I raise the PropertyChanged event for the second one (the alias) when the first one is changed.

NOTE: I'm using DependencyObjects, not INotifyPropertyChanged (tried that, didn't work because my control is a ListVie sub-classed)

Something like this.....

protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
    base.OnPropertyChanged(e);
    if (e.Property == MyFirstProperty)
    {
        RaiseAnEvent( MySecondProperty ); /// what is the code that would go here?
    }    
}

If I were using an INotify I could do like this...

public string SecondProperty
{
    get
    {
        return this.m_IconPath;
    }
}

public string IconPath
{
    get
    {
        return this.m_IconPath;
    }
    set
    {
        if (this.m_IconPath != value)
        {
            this.m_IconPath = value;
        this.SendPropertyChanged("IconPath");
        this.SendPropertyChanged("SecondProperty");
        }
    }
}

Where can I raise PropertyChanged events on multiple properties from one setter? I need to be able to do the same thing, only using DependencyProperties.

Answer

Brett Ryan picture Brett Ryan · Jun 22, 2011

I ran into a similar problem where I have a dependency property that I wanted the class to listen to change events to grab related data from a service.

public static readonly DependencyProperty CustomerProperty = 
    DependencyProperty.Register("Customer", typeof(Customer),
        typeof(CustomerDetailView),
        new PropertyMetadata(OnCustomerChangedCallBack));

public Customer Customer {
    get { return (Customer)GetValue(CustomerProperty); }
    set { SetValue(CustomerProperty, value); }
}

private static void OnCustomerChangedCallBack(
        DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
    CustomerDetailView c = sender as CustomerDetailView;
    if (c != null) {
        c.OnCustomerChanged();
    }
}

protected virtual void OnCustomerChanged() {
    // Grab related data.
    // Raises INotifyPropertyChanged.PropertyChanged
    OnPropertyChanged("Customer");
}