【问题标题】:How to implement the relationship between wpf Usercontrol and Data Object?如何实现wpf Usercontrol和Data Object的关系?
【发布时间】:2015-07-28 14:20:58
【问题描述】:

我有一个 UserControl 和一个数据对象,我想将它们绑定在一起,因此 WPF 用户控件始终在对象中呈现数据:

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

    }
}

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

【问题讨论】:

    标签: c# wpf xaml mvvm user-controls


    【解决方案1】:

    来自 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}" />
    

    我的最后一句话是建议您使用像 PrismCaliburn.Micro 这样的 MVVM 框架

    编辑:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-31
      • 2018-05-26
      • 1970-01-01
      • 1970-01-01
      • 2010-10-27
      • 2023-03-31
      • 1970-01-01
      相关资源
      最近更新 更多