Reputation: 563
I need to override the metadata of the DataContextProperty in my ContentControl to associate a PropertyChangedCallback.
As i know this is only allowed in the static constructor, but the PropertyChangedCallback can't be a static function. Is there a nicer way to achieve this?
static cunstructor:
static ListAndDetailsControl() {
DataContextProperty.OverrideMetadata(typeof(ListAndDetailsControl), new FrameworkPropertyMetadata(new PropertyChangedCallback(OnDataContextChanged)));
}
function that should be called on property changed:
private void OnDataContextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {}
Upvotes: 1
Views: 146
Reputation: 7325
OverrideMetadata
must not be mandatory in a static constructor(but it should be there). You can put it e.g. in Button.Click
event handler.
PropertyChangedCallback can't be a static function
It's wrong. PropertyChangedCallback can be a static function.
The problem is that if somebody has already registered/overridden the metadata for the property, then you will get an exception.
See on MSDN:
Also, metadata can only be overridden once per type. Subsequent attempts to override metadata on the same type will raise an exception.
To track changes on DataContext just use appropriate event ContentControl.DataContextChanged
.
<ContentControl DataContextChanged="OnDataContextChanged">
To avoid a code behind use a behavior handling DataContextChanged
.
Upvotes: 1