开发者

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: " + val开发者_如何学Pythonue); }
}

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);


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).


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜