Wpf – Custom Dependency Properties and TwoWay binding in WPF

data-bindingdependency-propertieswpf

We have an object that derives from DependencyObject, and implements some DependencyProperties.

Basically something like this:

class Context : DependencyObject {
   public static readonly DependencyProperty NameProperty =
   DependencyProperty.Register ("Name", typeof (string), typeof (Context), new PropertyMetadata (""));
    public string Name {
        get {
            return (string)this.GetValue (NameProperty);
        }
        set {
            this.SetValue (NameProperty, value);
        }
    }
}

This works, the property is setup, can be bound, etc. The issue comes when I bind TO the propery from WPF, using a TwoWay bind. The TwoWay part never actually happens, WPF never calls the set of this property. I have set my binding up like this:

<TextBox Text="{Binding Path=Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

In this case, typing in the text box should immediately update the Name property, but it does not. If I change the Name property to be a regular POCO property, it works (though the other side of the TwoWay obviously doesn't unless I implement INotifyPropertyChanged).

What am I doing wrong here? This should be a really simple thing to do, but it's causing me no end of headaches.

Best Answer

This is expected behavior. The CLR property is merely a wrapper around the underlying DependencyProperty. WPF often optimizes by calling GetValue and SetValue directly. If you need custom logic to execute then use the metadata of the DependencyProperty.

Related Topic