Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setters not run on Dependency Properties?

Just a short question, to clarify some doubts. Are setters not run when an element is bound to a dependency property?

public string TextContent
{
    get { return (string)GetValue(TextContentProperty); }
    set { SetValue(TextContentProperty, value); Debug.WriteLine("Setting value of TextContent: " + value); }
}

public static readonly DependencyProperty TextContentProperty =
    DependencyProperty.Register("TextContent", typeof(string), typeof(MarkdownEditor), new UIPropertyMetadata(""));

...

<TextBox Text="{Binding TextContent}" />

As I noticed the below in my setter does not run

Debug.WriteLine("Setting value of TextContent: " + value);
like image 472
Jiew Meng Avatar asked Nov 19 '10 13:11

Jiew Meng


2 Answers

The WPF binding engine calls GetValue and SetValue directly (bypassing the property setters and getters). You need the property to be there so it can be supported in the XAML markup (and compile correctly).

like image 121
Dean Chalk Avatar answered Nov 03 '22 08:11

Dean Chalk


To create a DependencyProperty, add a static field of type DepdencyProperty to your type and call DependencyProperty.Register() to create an instance of a dependency property. The name of the DependendyProperty must always end with ...Property. This is a naming convention in WPF.

To make it accessable as a normal .NET property you need to add a property wrapper. This wrapper does nothing else than internally getting and setting the value by using the GetValue() and SetValue() Methods inherited from DependencyObject and passing the DependencyProperty as key.

Do not add any logic to these properties, because they are only called when you set the property from code. If you set the property from XAML the SetValue() method is called directly.

Each DependencyProperty provides callbacks for change notification, value coercion and validation. These callbacks are registered on the dependency property.

source: http://www.wpftutorial.net/DependencyProperties.html

like image 53
Kishore Kumar Avatar answered Nov 03 '22 08:11

Kishore Kumar