如何实现wpf Usercontrol与Data Object的关系?

How to implement the relationship between wpf Usercontrol and Data Object?

我有一个 UserControl 和一个数据对象,我想将它们绑定在一起,以便 WPF UserControl 始终在对象中显示数据:

public partial class PersonRectangle : UserControl
{
    public PersonRectangle()
    {
        InitializeComponent();
    }
}
public class Person
{
    public string fname;
    public string lname;
    public Person()
    {

    }
}

将任何 Person 连接到关联的 wpf 视图的最佳方法是什么?我应该在部分 class PersonRectangle 中添加 Person 类型的 属性 吗?考虑到 MVVM 范例,我应该怎么做?

来自 UserControl 的 DataContext 属性 是 mvvm 实现的关键,Person 是您的模型,不应直接暴露给 View,而应通过 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));
            }
        }
}

然后在您的视图(用户控件)中:

public partial class PersonRectangle : UserControl
{
    public PersonRectangle()
    {
        InitializeComponent();
        DataContext = new PersonViewModel();
    }
}

您已经设置了 DataContext,因此您可以将视图控件绑定到 Person 属性,请注意此处使用 ViewModel 中的 Person 属性:

<TextBox Text="{Binding Path=Person.Name, Mode=TwoWay}" />

我最后的话是建议您使用像 Prism or Caliburn.Micro

这样的 MVVM 框架

EDIT:

您应该考虑将 Person 数据公开为属性,而不是像现在那样公开为 public 变量。