public class Person
{ public string ID { get; set; } public string Name { get; set; } } <StackPanel Margin="10" Orientation="Horizontal" Height="30" x:Name="PersonPanel">
<TextBlock Text="ID:" VerticalAlignment="Center"/> <TextBox Width="100" Text="{Binding Path=ID}" VerticalAlignment="Center"/> <TextBlock Text="Name:" VerticalAlignment="Center" Margin="20 0 0 0"/> <TextBox Width="100" Text="{Binding Path=Name}" VerticalAlignment="Center"/> <Button Content="Change Properties" x:Name="ChangeButton" Margin="20 0 0 0"/> </StackPanel> 然后在后台代码中添加数据源(设置DataContext属性)。 Person p= new Person() { ID="001", Name="TestPerson" };
PersonPanel.DataContext = p; ChangeButton.Click += (s0, e0) => { p.ID = "002"; p.Name = "TestPerson2"; }; ”依赖项属性支持属性变更通知“即属性值发生变化时,UI自动发生变化 让我们的类实现INotifyPropertyChanged接口。为了方便代码复用,我们可以使用一个基类来实现。 public class ModelBase : INotifyPropertyChanged
{ public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } public class Person : ModelBase
{ private string Id; public string ID { get { return Id; } set { Id = value; OnPropertyChanged("ID"); } } private string name; public string Name { get { return name; } set { name = value; OnPropertyChanged("Name"); } } } |
|