7

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.

Giffyguy
  • 20,378
  • 34
  • 97
  • 168
Matt Holmes
  • 1,055
  • 1
  • 8
  • 22

2 Answers2

11

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.

Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
  • Geez, I'm an idiot. You are 100% correct, the value itself is set correctly, but the setter is never called, which is what through me off. Thanks. – Matt Holmes Apr 29 '09 at 17:31
2

After this issue cost me some time:

For those of you who have the same problem, but - like me - don't see the solution in the answer above:

To support inheritance of the DataContext, the custom class (Context in this case) has to be derived from FrameworkElement rather than DependencyObject. That's all.

Marc

Marc
  • 12,706
  • 7
  • 61
  • 97