<Label>请输入姓名:</Label>
<TextBoxBackground="SkyBlue">
<!--使用属性元素语法绑定到Person类,指定Path为PersonName公共属性-->
<TextBox.Text>
<Binding Source="{StaticResource myDataSource}"Path="PersonName" Mode="TwoWay"UpdateSourceTrigger="PropertyChanged"/>
</TextBox.Text>
</TextBox>
<StackPanelOrientation="Horizontal">
<Label>输入的名字:</Label>
<!--使用Source属性获取更新后的属性值,由于Person类实现了INotifyPropertyChanged接口,因此更改会立即被显示-->
<TextBlock Background="Orange"Text="{Binding Source={StaticResource myDataSource},Path=PersonName}" Width="100" Height="30"HorizontalAlignment="Left"/>
</StackPanel>
//实现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));
}
}
}