Rock3rRullz
Rock3rRullz

Reputation: 465

Dependency Property Call in code behind

I have created a custom UserControl with some Dependency properties.
This custom control is hosted on a Window.
When I try to get a value from a DependecyProperty in code behind it doesn't work.

public static readonly DependencyProperty ValueDp = DependencyProperty.Register("Value", typeof(string), typeof(MyCustomUserControl), new FrameworkPropertyMetadata(string.Empty, OutputHandler));

public string Value
{
   get { return (string)GetValue(ValueDp); }
   set { SetValue(ValueDp, value); }
}

private static void OutputHandler(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
   var temp= dependencyObject as MyCustomUserControl;
   if (temp!= null)
   {
      dependencyObject.SetValue(ValueDp,temp._conversionValue);
   }
}

On the host I have put a button and when I click on it, I want to read the value stored in the DP, but I will always get the default value set in DP.

Any ideas what I`m doing wrong here?

Regards

Upvotes: 0

Views: 717

Answers (2)

Sandesh
Sandesh

Reputation: 3004

As @Alberto has said the OldValue and NewValue are the properties which hold the value of the DependencyProperty. The above properties are found in dependencyPropertyChangedEventArgs. In your Handler the member dependencyObject and temp refer to the same object.

Upvotes: 0

Alberto
Alberto

Reputation: 15951

I think that in the OutputHandler method you are always discarding the new value assigned to the property (dependencyPropertyChangedEventArgs.NewValue)

Upvotes: 1

Related Questions