WPF绑定到变量/ DependencyProperty

我正在玩WPF Binding和变量。 显然,只能绑定DependencyProperties。 我提出了以下内容,它完全正常:代码隐藏文件:

public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } public string Test { get { return (string)this.GetValue(TestProperty); } set { this.SetValue(TestProperty, value); } //set { this.SetValue(TestProperty, "BBB"); } } public static readonly DependencyProperty TestProperty = DependencyProperty.Register( "Test", typeof(string), typeof(MainWindow), new PropertyMetadata("CCC")); private void button1_Click(object sender, RoutedEventArgs e) { MessageBox.Show(Test); Test = "AAA"; MessageBox.Show(Test); } } 

XAML:

    

两个TextBoxes另一个更新。 按钮将它们设置为“AAA”。

但是现在我将Setter函数替换为注释掉的函数(模拟给定值的某些操作)。 我希望每当属性值改变时,它将被重置为“BBB”。 当您按下按钮时,即在代码中设置属性时,它会这样做。 但它确实不会影响WPF Bindings,也就是说你可以改变TextBox内容,从而改变属性,但显然从未调用过Setter。 我想知道为什么会这样,以及如何实现预期的行为。

永远不会保证调用依赖属性的CLR属性包装器,因此,您不应该在那里放置任何其他逻辑。 无论何时在更改DP时需要其他逻辑,都应使用属性更改的回调。

在你的情况下……

 public string Test { get { return (string)this.GetValue(TestProperty); } set { this.SetValue(TestProperty, value); } } public static readonly DependencyProperty TestProperty = DependencyProperty.Register("Test", typeof(string), typeof(MainWindow), new PropertyMetadata("CCC", TestPropertyChanged)); private static void TestPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e) { MainWindow mainWindow = source as MainWindow; string newValue = e.NewValue as string; // Do additional logic } 

您的更改不会影响绑定,因为XAML将直接调用SetValue,而不是调用属性setter。这是依赖属性系统的工作方式。当注册依赖项属性时,可以指定默认值。此值从GetValue返回并且是您的属性的默认值。

请查看下面的链接,并阅读Robert Rossney的post以获得公平的概述

WPF:依赖属性与常规CLR属性的区别是什么?

也不要错过

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

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

另请注意,与普通CLR属性不同,您在setter中编写的任何自定义逻辑都不会在Dependency Properties中执行,而是必须使用PropertyChangedCallback机制

http://blogs.msdn.com/b/delay/archive/2010/03/23/do-one-thing-and-do-it-well-tip-the-clr-wrapper-for-a-dependencyproperty-应该-DO-其在职和全无,more.aspx