【发布时间】:2011-06-14 01:43:12
【问题描述】:
这次我的测试代码显示了一个文本框和两个文本块。 TextBox 和第一个 TextBlock 通过双向数据绑定连接到数据上下文的字符串属性。第二个 TextBlock 由 TextBox 的 TextChanged 事件上的事件处理程序更新,将其设置为字符串属性的当前值。
当窗口加载时,两个 TextBlock 都被正确初始化。但是当我输入文本框时,只有第二个更新。第二个 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,你应该阅读它。
-
"要使 TwoWay 和 OneWayToSource 绑定起作用,源对象需要提供属性更改通知。"正确的例子在How to: Implement Property Change Notification
-
我不是想“举个例子”。您应该阅读包含该部分的完整手册。您肯定会遇到其他问题,其中绝大多数都在此处进行了解释,如果您不阅读它,您最终会不必要地在这里提问。