這次我的測試代碼顯示一個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