Setter不在依赖属性上运行?

Jie*_*eng 37 wpf setter dependency-properties

只是一个简短的问题,澄清一些疑问.当元素绑定到依赖项属性时,是否运行setter?

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(""));
Run Code Online (Sandbox Code Playgroud)

...

<TextBox Text="{Binding TextContent}" />
Run Code Online (Sandbox Code Playgroud)

正如我注意到我的setter中的下面没有运行

Debug.WriteLine("Setting value of TextContent: " + value);
Run Code Online (Sandbox Code Playgroud)

Dea*_*alk 50

在WPF绑定引擎调用GetValueSetValue直接(绕过属性getter和setter方法).您需要该属性,因此可以在XAML标记中支持(并正确编译).


Kis*_*mar 42

要创建DependencyProperty,请将类型为DepdencyProperty的静态字段添加到您的类型,并调用DependencyProperty.Register()以创建依赖项属性的实例.DependendyProperty的名称必须始终以...属性结尾.这是WPF中的命名约定.

要使其可以作为普通的.NET属性进行访问,您需要添加属性包装器.这个包装器除了通过使用从DependencyObject继承并将DependencyProperty作为键传递的GetValue()和SetValue()方法在内部获取和设置值之外别无其他.

不要向这些属性添加任何逻辑,因为只有在从代码设置属性时才会调用它们.如果从XAML设置属性,则直接调用SetValue()方法.

每个DependencyProperty都提供变更通知,值强制和验证的回调.这些回调在依赖项属性上注册.

来源:http://www.wpftutorial.net/DependencyProperties.html