<Label>請(qǐng)輸入姓名:</Label>
<TextBoxBackground="SkyBlue">
<!--使用屬性元素語(yǔ)法綁定到Person類(lèi),指定Path為PersonName公共屬性-->
<TextBox.Text>
<Binding Source="{StaticResource myDataSource}"Path="PersonName" Mode="TwoWay"UpdateSourceTrigger="PropertyChanged"/>
</TextBox.Text>
</TextBox>
<StackPanelOrientation="Horizontal">
<Label>輸入的名字:</Label>
<!--使用Source屬性獲取更新后的屬性值,由于Person類(lèi)實(shí)現(xiàn)了INotifyPropertyChanged接口,因此更改會(huì)立即被顯示-->
<TextBlock Background="Orange"Text="{Binding Source={StaticResource myDataSource},Path=PersonName}" Width="100" Height="30"HorizontalAlignment="Left"/>
</StackPanel>
//實(shí)現(xiàn)INotifyPropertyChanged
//以支持單向和雙向綁定
public class Person :INotifyPropertyChanged
{
private string _personName;
public string PersonName
{
get
{
return_personName;
}
set
{
_personName = value;
OnPropertyChanged("PersonName");
}
}
public Person()
{
}
public Person(string value)
{
this._personName = value;
}
public event PropertyChangedEventHandlerPropertyChanged;
protected void OnPropertyChanged(stringpropertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if(handler != null)
{
handler(this, newPropertyChangedEventArgs(propertyName));
}
}
}