代码改变世界

使用 MVVMLight 绑定数据

2014-07-14 10:52  Andrew.Wangxu  阅读(1299)  评论(0编辑  收藏  举报

MVVM

如果你还不知道如何在VS中加入MVVMLight的引用,那么建议你先翻阅这篇文章:在VS中安装/使用 MVVMLight

这篇文章主要是介绍如何使用MVVMLight来绑定数据到界面中(View),以此来了解MVVMLight的一些基础的类的用法。

文章底部会提供本示例的源码下载。

 

MVVMLight绑定数据示例

好了,我们在新建了两个项目,分别是“MVVMLight的主程序” 与  “Model层”,运行的效果及解决方案结构如下:

MVVMLightBinding_1

其实很简单,就是绑定了一个数据源而已,编写的代码也不多,下面我们来一步一步的实现使用MVVMLight来绑定数据,并了解其中的细节。

 

如何实现?

我这里使用的是.NET 4.5  , 你可以使用至少4.0以上的版本来实现这个项目(选择4.0/4.5 要选择想要的MVVMLight的引用文件),下面依次建立两个项目来实现。

1.建立Model层的项目

新建了一个命名为“MyModel”的类库项目,其中引用了MVVMLight相关程序集,然后包含一个User类即可。User.cs代码如下:

  1. using GalaSoft.MvvmLight;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Collections.ObjectModel;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8.  
  9. namespace MyModel
  10. {
  11.     public class User : ObservableObject
  12.     {
  13.         private int _id;
  14.         /// <summary>
  15.         /// ID
  16.         /// </summary>
  17.         public int ID
  18.         {
  19.             get { return _id; }
  20.             set
  21.             {
  22.                 _id = value;
  23.                 RaisePropertyChanged("ID");
  24.             }
  25.         }
  26.  
  27.         private string _name;
  28.         /// <summary>
  29.         /// 名称
  30.         /// </summary>
  31.         public string Name
  32.         {
  33.             get { return _name; }
  34.             set
  35.             {
  36.                 _name = value;
  37.                 RaisePropertyChanged("Name");
  38.             }
  39.         }
  40.  
  41.         private string _domain;
  42.         /// <summary>
  43.         /// 网站域名
  44.         /// </summary>
  45.         public string Domain
  46.         {
  47.             get { return _domain; }
  48.             set
  49.             {
  50.                 _domain = value;
  51.                 RaisePropertyChanged("Domain");
  52.             }
  53.         }
  54.  
  55.  
  56.         #region 模拟数据获取
  57.         /// <summary>
  58.         /// 模拟测试数据
  59.         /// </summary>
  60.         /// <returns></returns>
  61.         public static ObservableCollection<User> GetUserList()
  62.         {
  63.             ObservableCollection<User> list = new ObservableCollection<User>();
  64.             list.Add(new User() { ID = 1, Name = "王旭", Domain = "www.wxzzz.com" });
  65.             list.Add(new User() { ID = 2, Name = "王旭博客", Domain = "www.wxzzz.com" });
  66.  
  67.             return list;
  68.         }
  69.         #endregion
  70.     }
  71. }
  72.  

User类主要继承了 ObservableObject 这个对象,这个对象其实也是ViewModelBase的父类,我们下面会用到。该类主要是实现了属性变更通知接口,如我们用到的:RaisePropertyChanged("");

User 类中包含了3个字段分别是

  1. int ID
  2. string Name
  3. string Domain

然后包含了一个静态的GetUserList()方法。其他的就没什么了,这个项目就建立完毕了。

 

2.建立主程序项目

我这里使用的是WPF项目,当然你也可以建立其他类型的项目。建立好WPF项目之后,我们需要在项目中建立如下结构的文件

  • View -> UserView.xaml
  • ViewModel -> UserViewModel.cs

View 文件夹用于存放向用户展示的UI界面。

ViewModel 用于存放业务逻辑代码。

 

首先编写 UserViewModel 的代码如下

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7.  
  8. using GalaSoft.MvvmLight;
  9. using MyModel;
  10.  
  11. namespace MVVMLightDemo.ViewModel
  12. {
  13.     public class UserViewModel : ViewModelBase
  14.     {
  15.         public UserViewModel()
  16.         {
  17.             //初始化数据
  18.             _userData = User.GetUserList();
  19.         }
  20.  
  21.         private ObservableCollection<User> _userData;
  22.         /// <summary>
  23.         /// 用户信息数据
  24.         /// </summary>
  25.         public ObservableCollection<User> UserData
  26.         {
  27.             get { return _userData; }
  28.             set
  29.             {
  30.                 _userData = value;
  31.                 RaisePropertyChanged("UserData");
  32.             }
  33.         }
  34.  
  35.     }
  36. }
  37.  

每个ViewModel类都将继承MVVMLight的 ViewModelBase 为父类, 不过不要忘了 using GalaSoft.MvvmLight;  。继承之后就可以调用父类的 RaisePropertyChanged("属性名") 来实现属性变更通知了,在值有改变的时候那么UI界面绑定了该值的情况下 就会收到通知跟随改变。

 

我在该类的构造函数中,对 UserData 进行了初始化,把数据给赋值上去了,那么在接下来的View中绑定 UserData 才会出现数据。

 

接下来开始编写 UserView.xaml 的代码如下

  1. <Window x:Class="MVVMLightDemo.View.UserView"
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.         Title="UserView" Height="300" Width="300">
  5.     <Grid>
  6.         <DataGrid ItemsSource="{Binding UserData}"></DataGrid>
  7.     </Grid>
  8. </Window>

其实代码就只有一行,也就是 <DataGrid ItemsSource="{Binding UserData}"></DataGrid>这样代码,让其 DataGrid 绑定字段 UserData 即可。

仅仅这样还不行,我们还需要让View与ViewModel关联起来,那么需要设置这个View的数据上下文。 在后台编写如下代码

  1. public UserView()
  2. {
  3.      this.DataContext = new UserViewModel();
  4.      InitializeComponent();
  5. }

其实代码也只有一行,也就是 this.DataContext = new UserViewModel(); 即可。

 

至此我们的代码就编写完成了,实现了MVVMLight中的数据绑定。

而MainWindow.xaml我仅仅放置了一个按钮使用了 Click事件在xaml的后台代码中直接弹出了UserView窗口。后面再来改进这些代码。

示例源码下载:MVVMLightDemo_1

更多的MVVMLight使用,请返回查阅《MVVMLight 设计模式系列使用文章,欢迎各位Coder补充。

转载请注明:王旭博客 » 使用 MVVMLight 绑定数据