分享

WPF数据绑定-绑定到用户数据

 SanySmile 2013-06-03
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"); }
}
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多