
代码隐藏文件:
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:
<Window x:Class="WpfApplication3.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:diag="clr-namespace:System.Diagnostics;assembly=windowsBase" title="MainWindow" Height="350" WIDth="525" DataContext="{Binding relativeSource={relativeSource Self}}"><GrID> <TextBox Height="31" HorizontalAlignment="left" margin="84,86,0" name="textBox1" VerticalAlignment="top" WIDth="152" Text="{Binding Test,Mode=TwoWay,diag:PresentationTraceSources.TraceLevel=High}"/> <button Content="button" Height="23" HorizontalAlignment="left" margin="320,85,0" name="button1" VerticalAlignment="top" WIDth="75" Click="button1_Click" /> <TextBox Height="31" HorizontalAlignment="left" margin="84,138,0" name="textBox2" Text="{Binding Test,Mode=TwoWay}" VerticalAlignment="top" WIDth="152" /></GrID> 两个TextBoxes另一个更新.按钮将它们设置为“AAA”.
但是现在我将Setter函数替换为注释掉的函数(模拟给定值的某些 *** 作).我希望每当属性值改变时,它将被重置为“BBB”.当您按下按钮时,即在代码中设置属性时,它会这样做.但它确实不会影响WPF Bindings,也就是说你可以改变TextBox内容,从而改变属性,但显然从未调用过Setter.
我想知道为什么会这样,以及如何实现预期的行为.
在你的情况下..
public string Test{ get { return (string)this.GetValue(TestProperty); } set { this.SetValue(TestProperty,value); }}public static Readonly DependencyProperty TestProperty = DependencyProperty.Register("Test",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} 总结 以上是内存溢出为你收集整理的c# – WPF绑定到变量/ DependencyProperty全部内容,希望文章能够帮你解决c# – WPF绑定到变量/ DependencyProperty所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)