这次我的测试代码显示一个TextBox和两个TextBlocks。 TextBox和第一个TextBlock通过双向数据绑定连接到数据上下文的字符串属性。第二个TextBlock由TextBox的TextChanged事件上的事件处理程序更新,该事件处理程序将其设置为字符串属性的当前值。另一个WPF绑定语法问题
当窗口加载时,两个TextBlocks都已正确初始化。但是当我输入TextBox时只有第二个更新。第二个TextBlock被更新的事实证实TextBox与字符串属性的双向绑定正在工作。但为什么第一个TextBlock不会更新?
标记:
<Window x:Class="DataBinding.SimpleDataBinding"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="SimpleDataBinding" Height="300" Width="300" >
<StackPanel>
<TextBox Name="txtPerson" Text="{Binding Path=Person, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Name="tbPerson1" Text="{Binding Path=Person, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Name="tbPerson2" />
</StackPanel>
</Window>
后面的代码:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace DataBinding
{
public partial class SimpleDataBinding : Window
{
public string Person { get; set; }
public SimpleDataBinding() {
InitializeComponent();
Person = "George";
DataContext = this;
txtPerson.TextChanged += new TextChangedEventHandler(txtPerson_TextChanged);
}
private void txtPerson_TextChanged(object sender, TextChangedEventArgs e) {
tbPerson2.Text = Person;
}
}
}
[The manual](http://msdn.microsoft.com/en-us/library/ms752347.aspx),您应该阅读它。 – 2011-06-14 03:45:49
“为了使双向和OneWayToSource绑定正常工作,源对象需要提供属性更改通知。”正确的示例是在[如何:实现属性更改通知](http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx) – howard39 2011-06-14 16:32:59
我没有试图*“举一个例子“*。您应该阅读包含该部分的**整个手册**。你肯定会遇到其他问题,其中绝大多数都会在那里解释,如果你没有阅读它,你会不必要地在这里问问题。 – 2011-06-14 18:02:24