WPF绑定到变量/DependencyProperty我在玩WPF绑定和变量。显然,只能绑定DependencyProperties。我想出了以下内容并且它完美运行:代码隐藏文件:publicpartialclassMainWindow:Window}publicstringTest{get{return(string)this.GetValue(TestProperty);}set{this.SetValue(TestProperty,value);}//set{this.SetValue(TestProperty,"BBB");}}publicstaticreadonlyDependencyPropertyTestProperty=DependencyProperty.Register("Test",typeof(string),typeof(MainWindow),newPropertyMetadata("CCC"));privatevoidbutton1_Click(objectsender,RoutedEventArgse){MessageBox.Show(Test);测试=“AAA”;MessageBox.Show(测试);XAML:两个TextBoxes另一个更新。按钮将它们设置为“AAA”。但现在我用注释掉的函数替换了Setter函数(模拟给定值的某些操作)。我希望在属性值更改时将其重置为“BBB”。当您按下按钮时,即当您在代码中设置属性时,它会执行此操作。但它不会影响WPF绑定,即您可以更改TextBox内容,从而更改属性,但显然永远不会调用Setter。我想知道为什么会这样,以及如何实现预期的行为。永远不能保证调用依赖属性的CLR属性包装器,因此,您不应在其中放置任何其他逻辑。每当您在更改DP时需要额外的逻辑时,您应该使用属性更改回调。在你的情况下......publicstringTest{get{return(string)this.GetValue(TestProperty);}set{this.SetValue(TestProperty,value);}}publicstaticreadonlyDependencyPropertyTestProperty=DependencyProperty.Register("Test",typeof(string),typeof(MainWindow),newPropertyMetadata("CCC",TestPropertyChanged));privatestaticvoidTestPropertyChanged(DependencyObjectsource,DependencyPropertyChangedEventArgse){MainWindowmainWindow=sourceasMainWindow;字符串值为e.Newstring;//执行附加逻辑}您的更改不会影响绑定,因为XAML将直接调用SetValue而不是调用属性设置器。这就是依赖属性系统的工作原理。注册依赖属性时,可以指定一个默认值。该值从GetValue返回,是您的属性的默认值。查看下面的链接,并阅读RobertRossney的帖子以获得WPF的公平概述:What'stheDifferenceBetweenDependencyPropertiesandRegularCLRProperties?也不要错过http://msdn.microsoft.com/en-us/library/ms753358.aspx和http://msdn.microsoft.com/en-us/library/ms752914.aspx另请注意,使用普通CLRproperties不同的是,您在setter中编写的任何自定义逻辑都不会在DependencyProperties中执行,您必须使用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-should-do-it'sin-serviceandnothing-more.aspx以上是C#学习教程:WPF绑定tovariables/DependencyProperty分享的所有内容,如果对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
