WPF dependency property not working

I have my own dependency property defined as follows:

public static readonly DependencyProperty MyDependencyProperty = DependencyProperty.Register( "MyCustomProperty", typeof(string), typeof(MyClass)); private string _myProperty; public string MyCustomProperty { get { return (string)GetValue(MyDependencyProperty); } set { SetValue(MyDependencyProperty, value); } } 

Now I will try to set this property in XAML

 <controls:TargetCatalogControl MyCustomProperty="Boo" /> 

But the installer never gets into DependencyObject! Although this happens when I change the property as a regular property, not Dep Prop

+7
c # wpf xaml
source share
3 answers

Try it.

  public string MyCustomProperty { get { return (string)GetValue(MyCustomPropertyProperty); } set { SetValue(MyCustomPropertyProperty, value); } } // Using a DependencyProperty as the backing store for MyCustomProperty. This enables animation, styling, binding, etc... public static readonly DependencyProperty MyCustomPropertyProperty = DependencyProperty.Register("MyCustomProperty", typeof(string), typeof(TargetCatalogControl), new UIPropertyMetadata(MyPropertyChangedHandler)); public static void MyPropertyChangedHandler(DependencyObject sender, DependencyPropertyChangedEventArgs e) { // Get instance of current control from sender // and property value from e.NewValue // Set public property on TaregtCatalogControl, eg ((TargetCatalogControl)sender).LabelText = e.NewValue.ToString(); } // Example public property of control public string LabelText { get { return label1.Content.ToString(); } set { label1.Content = value; } } 
+15
source share

This is not the case unless you name it manually. There is a handler with a changed property, which you can add to the call to the DependancyProperty constructor to be notified when the property changes.

Call this constructor:

http://msdn.microsoft.com/en-us/library/ms597502.aspx

With the PropertyMetadata instance created by this constructor:

http://msdn.microsoft.com/en-us/library/ms557327.aspx

EDIT: Also, you are not properly implementing the dependency property. Your get and set should use GetValue and SetValue respectively, and you should not have a class member to store the value. The DP member name must also be {PropertyName}Property , for example. MyCustomPropertyProperty if get / set and the property name as registered by MyCustomProperty . See http://msdn.microsoft.com/en-us/library/ms753358.aspx for more details.

Hope this helps.

+2
source share

Perhaps you are using MVVM and overriding the DataContext of your view?

If you do this, the event to change MyCustomProperty will be raised in the original DataContext, and not in the new ViewModel.

+1
source share

All Articles