MVVM里面:把MODEL转换为VIEWMODE

摘要:MVVM里面把数据库的MODEL转化为页面需要的VIEWMODEL,今天偷偷的学到了,记录一下,以后备用。

EducationInfo是我定义的VIEWMODEL,页面展示个性化的数据

args.Result是数据库里面的表结构model 

需求:

页面有一个列表,需要显示个性化的数据,其中有一个字段是显示数据库里面两个字段的合成字段,数据库存的时候是开始时间:1987-8-8与结束时间1988-8-8

但是这一列数据最终展示的时候是 1987-1988。由于这个需求,也就写了VIEWMODEL这个东西。

 

我页面显示数据的时候是用BINDING的方法, 


1.(1)mvvm里面,只要维护这个东西,比如增加一条记录在页面上,就可以直接维护ObservableCollection,人家说这个是标准MVVM带的属性
   private ObservableCollection<EducationInfo> _education_info;
   (2)绑定的时候是这么绑定的:args.Result是model
   _education_info = new ObservableCollection<EducationInfo>(args.Result.Select(ei => new EducationInfo(ei)));

  全部代码
   private ObservableCollection<EducationInfo> _education_info; //viewmode
   public void BindDate(string strUserId)
        {
            Helper.XExpertProvider.GetEducationItem("8259cb9f-8e2b-4bcd-84a2-969918e9a13e", null,
                 (s, args) =>
                 {
                     if (args.Error != null)
                     {
                         MessageBox.Show(args.Error.Message);
                     }
                     if (args.Cancelled == true) return;
                    _education_info = new ObservableCollection<EducationInfo>(args.Result.Select(ei => new EducationInfo(ei)));
                     GVList.ItemsSource = _education_info;
                 }
            );

        }

 

2.不是标准的MVVM,但是可以实现功能的
  1.我定义的VIEWMODE
  private IList<EducationInfo> _education_info;
  2.把MODEL转化为VIEWMODEL
      private IList<EducationInfo> _education_info;
      public void BindDate(string strUserId)
        {
            Helper.XExpertProvider.GetEducationItem("8259cb9f-8e2b-4bcd-84a2-969918e9a13e", null,
                 (s, args) =>
                 {
                     if (args.Error != null)
                     {
                         MessageBox.Show(args.Error.Message);
                     }
                     if (args.Cancelled == true) return;
                      //LINQ语句的表达法等效与下面的lamda 表达式
                     //_education_info = (from ei in args.Result select new EducationInfo(ei)).ToList();
                    
                     //lamda 表达式
                     _education_info = args.Result.Select(ei => new EducationInfo(ei)).ToList();               
                     GVList.ItemsSource = _education_info;
                 }
            );

        }

posted @ 2012-03-19 16:00  红萝卜  阅读(1569)  评论(0编辑  收藏  举报