C# 如何实现wpf Usercontrol和数据对象之间的关系?
我有一个C# 如何实现wpf Usercontrol和数据对象之间的关系?,c#,wpf,xaml,mvvm,user-controls,C#,Wpf,Xaml,Mvvm,User Controls,我有一个UserControl和一个数据对象,我想将它们绑定在一起,以便WPF UserControl始终显示对象中的数据: public partial class PersonRectangle : UserControl { public PersonRectangle() { InitializeComponent(); } } public class Person { public string fname; public st
UserControl
和一个数据对象,我想将它们绑定在一起,以便WPF UserControl始终显示对象中的数据:
public partial class PersonRectangle : UserControl
{
public PersonRectangle()
{
InitializeComponent();
}
}
public class Person
{
public string fname;
public string lname;
public Person()
{
}
}
将任何人连接到关联的wpf视图的最佳方式是什么?我是否应该将类型为
Person
的属性添加到分部类PersonRectangle
?考虑到MVVM范例,我应该如何做到这一点?UserControl的DataContext属性是MVVM实现的关键,Person是您的模型,不应该直接向视图公开,而应该通过ViewModel对象公开
public class PersonViewModel: INotifyPropertyChanged
{
public PersonViewModel()
{
/*You could initialize Person from data store or create new here but not necessary.
It depends on your requierements*/
Person = new Person();
}
private Person person;
public Person Person{
get {return person;}
set {
if ( person != value){
person = value;
OnPropertyChanged()
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)
{
var eventHandler = this.PropertyChanged;
if (eventHandler != null)
{
eventHandler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
然后在您的视图(UserControl)中:
您已经设置了DataContext,以便可以将视图控件绑定到Person属性,请注意ViewModel中Person属性的用法:
<TextBox Text="{Binding Path=Person.Name, Mode=TwoWay}" />
我的最后一句话是建议您使用MVVM框架,如或
编辑:
您应该考虑将个人数据作为属性公开,而不是像现在一样公开变量。
<TextBox Text="{Binding Path=Person.Name, Mode=TwoWay}" />