The thing is I always want to bind controls against DataContext property. Because I don't like specifying Source in Binding expression. However, I do not want to bind DataContext property of my controls explicitly, but use another designated and self-descriptive properties, like Items or Plugins or whatever the purpose of control is. Now, I need a way to set DataContext property whenever that self-descriptive property truly determining the context of a control is set. Moreover, I want DataContext to always same as this property. How this can be done?
I tried specifying PropertyMetadata with callback that would set DataContext on newly received value. It doesn't work. Firstly, because this callback isn't being called for default value of a property. And secondly, and that is most interesting, I observed very strange behavior. Let me explain this using a callstack:
This is my PropertyMetadata with breakpoint in the callback:
new PropertyMetadata((d, e) => ((SearchSettings)d).DataContext = e.NewValue)
And this is the callstack (there are comments at the ends of the lines):
3. Bla-bla-bla.SearchSettings..cctor.AnonymousMethod__7(DependencyObject d, DependencyPropertyChangedEventArgs e) /* Setting property back to null. Why??? */
2. [External Code]
1. Bla-bla-bla.SearchSettings..cctor.AnonymousMethod__7(DependencyObject d, DependencyPropertyChangedEventArgs e) /* This is where the breakpoint hit first. Settings a new value to a property as a result of databinding. */
So, how do I do it? Or should I want to do it at all? BTW, I am new to WPF, so I could get it all wrong.