Brannon
Brannon

Reputation: 5414

dependent property in WPF -- how do I bind to it?

Suppose I have the following code in a WPF UserControl. I want to bind to Asset.ChildProperty. It doesn't work presently because I don't get notifications when the Asset property changes. How do I arrange things so that notifications trigger for the Asset property whenever AssetID changes?

public static readonly DependencyProperty AssetIdProperty = DependencyProperty.Register("AssetId", typeof(string), typeof(GaugeBaseControl));

[Browsable(false), DataMember]
public string AssetId
{
    get { return (string)GetValue(AssetIdProperty); }
    set { SetValue(AssetIdProperty, value); }
}

[DisplayName("Asset Item"), Category("Value Binding")]
public AssetViewModel Asset
{
    get { return Manager.Models.FirstOrDefault(m => m.Model.UniqueId == AssetId); }
    set
    {
        if (value == null)
            AssetId = string.Empty;
        else
            AssetId = value.Model.UniqueId;
    }
}

Upvotes: 1

Views: 407

Answers (2)

Ray Saltrelli
Ray Saltrelli

Reputation: 4218

You can specify a callback method in the PropertyMetadata of the DependencyProperty to be called when the value of a DependencyProperty changes and raise a PropertyChanged event from that callback method.

public class MyClass : DependencyObject, INotifyPropertyChanged
{

    public MyClass ()
    {
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public bool State
    {
        get { return (bool)this.GetValue(StateProperty); }
        set { this.SetValue(StateProperty, value); } 
    }

    public static readonly DependencyProperty StateProperty =
        DependencyProperty.Register(
            "State", 
            typeof(bool), 
            typeof(MyClass),
            new PropertyMetadata(
                false, // Default value
                new PropertyChangedCallback(OnDependencyPropertyChange)));

    private static void OnDependencyPropertyChange(
        DependencyObject d, 
        DependencyPropertyChangedEventArgs e)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(d, 
                new PropertyChangedEventArgs(e.Property.Name);
        }
    }
}

If you raising PropertyChanged events from the State property's setter then they will not fire when the property is bound because bindings invoke StateProperty directly, not State.

Upvotes: 2

myermian
myermian

Reputation: 32515

Implement INotifyPropertyChanged and raise the PropertyChanged event when Asset changes (in the setter method).

Upvotes: 1

Related Questions