什么是MVVM
MVVM即Model-View-ViewModel,通常适用于WPF或Silverlight开发。
MVC或MVP都是基于面向对象的设计模式,而MVVM是基于组件,数据驱动的设计模式。正是这一区别,造成大家对于MVVM学习起来比较费力。
我们可以通过下图来直观的理解MVVM设计模式:
- View:使用XAML呈现给用户的界面,负责与用户交互,接收用户输入,把数据展现给用户。
- Model:事物的抽象,开发过程中涉及到的事物都可以抽象为Model,例如姓名、年龄、性别、地址等属性。不包含方法,也不需要实现INotifyPropertyChanged接口。
- ViewModel:负责收集需要绑定的数据和命令,聚合Model对象,通过View类的DataContext属性绑定到View,同时也可以处理一些UI逻辑。
MVVM优点
MVVM简单示例
为了让大家直观地了解MVVM的编程模式,下面会用到前面讲到的数据绑定以及命令等知识。
1.新建WPF项目,名称WpfMVVM。在Model中添加用户类(User):
public class User : ICloneable
{
private int id;
private string name;
private int age;
private string sex;
private string address;
/// <summary>
/// 编号
/// </summary>
public int ID { get { return id; } set { id = value;} }
/// <summary>
/// 姓名
/// </summary>
public string Name { get { return name; } set { name = value;} }
/// <summary>
/// 年龄
/// </summary>
public int Age { get { return age; } set { age = value; } }
/// <summary>
/// 性别
/// </summary>
public string Sex { get { return sex; } set { sex = value; } }
/// <summary>
/// 地址
/// </summary>
public string Address { get { return address; } set { address = value; } }
/// <summary>
/// 使数据的复制变为深复制,需要实现ICloneable接口
/// </summary>
/// <returns></returns>
public object Clone()
{
return (Object)this.MemberwiseClone();
}
}
需要注意,后面ViewModel需要数值的复制,如果不实现ICloneable接口,那么将是浅复制,关于浅复制和深复制,请自行百度搜索,相关文章链接:https://blog.youkuaiyun.com/bigpudding24/article/details/48490145
2.在ViewModel中添加数据(ShowDataViewModel):
public class ShowDataViewModel
{
/// <summary>
/// 添加用户数据
/// </summary>
/// <returns></returns>
public ObservableCollection<User> GetUsers()
{
ObservableCollection<User> userList = new ObservableCollection<User>();
for (int i = 0; i < 15; i++)
{
userList.Add(new User() { ID = (i + 1), Name = "李" + (i + 1), Age = (20 + i), Sex = (i + 1) % 2 == 0 ? "女" : "男", Address = "菜园西" + (i + 1) + "号" });
}
return userList;
}
}
需要注意 ,集合请不要用List关键字,不然数据更新后,View是不会刷新数据的!请使用:ObservableCollection。
3.在ViewModel中创建命令绑定(DelegateCommands):
public class DelegateCommands : ICommand
{
//当命令可执行状态发生改变时,应当被激发
public event EventHandler CanExecuteChanged;
public Action<object> ExecuteCommand = null;
public Func<object, bool> CanExecuteCommand = null;
/// <summary>
/// 用于判断命令是否可以执行
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
if (CanExecuteCommand !=null)
{
return CanExecuteCommand(parameter);
}
else
{
return true;
}
}
/// <summary>
/// 命令执行
/// </summary>
/// <param name="parameter"></param>
public void Execute(object parameter)
{
if (ExecuteCommand !=null)
{
ExecuteCommand(parameter);
}
}
}
实现接口ICommand。
4.在ViewModel中进行业务处理(UserViewModel):
public class UserViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string PropertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
}
}
private ObservableCollection<User> userList;
/// <summary>
/// 用户集合
/// </summary>
public ObservableCollection<User> UserList
{
get
{
if (userList == null)
{
userList = new ObservableCollection<User>();
userList = new ShowDataViewModel().GetUsers();
}
return userList;
}
set {
if (userList == null)
{
userList = new ObservableCollection<User>();
}
userList = value;
OnPropertyChanged("UserList");
}
}
public User selectUser;
/// <summary>
/// 被选中的用户
/// </summary>
public User SelectUser
{
get
{
if (selectUser == null)
{
selectUser = new User();
}
return selectUser;
}
set
{
if (selectUser == null)
{
selectUser = new User();
}
selectUser = value; OnPropertyChanged("SelectUser");
}
}
/// <summary>
/// 注册命令
/// </summary>
private void RegisterCommands()
{
AddCommand = new DelegateCommands();
AddCommand.ExecuteCommand = new Action<object>(AddUser);
UpdateCommand = new DelegateCommands();
UpdateCommand.ExecuteCommand = new Action<object>(UpdateUser);
DeleteCommand = new DelegateCommands();
DeleteCommand.ExecuteCommand = new Action<object>(DeleteUser);
SelectionCommand = new DelegateCommands();
SelectionCommand.ExecuteCommand = new Action<object>(SelectionUser);
}
public UserViewModel()
{
RegisterCommands();
}
/// <summary>
/// 显示提示信息
/// </summary>
/// <param name="txt"></param>
public void MsgShow(string txt)
{
System.Windows.MessageBox.Show(txt);
//删除后清空选择用户
SelectUser = null;
}
#region 注册命令
/// <summary>
/// 新增用户
/// </summary>
public DelegateCommands AddCommand { get; set; }
/// <summary>
/// 更新用户
/// </summary>
public DelegateCommands UpdateCommand { get; set; }
/// <summary>
/// 删除用户
/// </summary>
public DelegateCommands DeleteCommand { get; set; }
/// <summary>
/// 选择用户
/// </summary>
public DelegateCommands SelectionCommand { get; set; }
public void AddUser(object parameter)
{
//新增用户的ID为【最小】编号
int id = 0;
for (int i = 0; i < UserList.Count; i++)
{
if (UserList[i].ID != (i + 1))
{
id = (i + 1);
break;
}
}
if (id == 0)
{
id = UserList.Max(a => a.ID) + 1;
}
UserList.Insert((id - 1), new User() { ID = id, Name = SelectUser.Name, Age = SelectUser.Age, Sex = SelectUser.Sex, Address = SelectUser.Address });
MsgShow("用户编号:" + id + "\n新增成功!");
}
public void UpdateUser(object parameter)
{
if (SelectUser.ID < 1)
{
MsgShow("请选择修改项!");
return;
}
//查找需要修改的对象
User user = UserList.Where(a => a.ID == SelectUser.ID).SingleOrDefault();
//查找需要修改的对象索引
int index = UserList.IndexOf(user);
//使数据的复制变为深复制,需要实现ICloneable接口
UserList[index]= (User)SelectUser.Clone();
MsgShow("用户编号:" + SelectUser.ID + "\n修改成功!");
}
public void DeleteUser(object parameter)
{
if (SelectUser.ID < 1)
{
MsgShow("请选择修改项!");
return;
}
User user = UserList.Where(a => a.ID == SelectUser.ID).SingleOrDefault();
UserList.Remove(user);
MsgShow("用户编号:" + SelectUser.ID + "\n删除成功!");
}
public void SelectionUser(object parameter)
{
DataGrid grid = (DataGrid)parameter;
//使数据的复制变为深复制,需要实现ICloneable接口
if (grid.SelectedItem!=null)
{
SelectUser = (User)((User)grid.SelectedItem).Clone();
}
}
#endregion
}
注意事项:需要实现接口INotifyPropertyChanged,不然数据更新后界面无法更新。
对于引用类型的值之间复制,是需要使用深复制,不然改动其中一个值,另一个值同时也会变更,使用方法: SelectUser = (User)((User)grid.SelectedItem).Clone();
关于AddUser方法,我为何不直接让ID去集合的最大值呢?因为几天前我在论坛看到一个帖子,按照他说的内容,特意这么做,请不要模仿!!!
5.在View中创建用户界面(MainWindow.xaml) :
<Window x:Class="WpfMVVM.View.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfMVVM.View"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="450" WindowStartupLocation="CenterScreen" ResizeMode="NoResize" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="5*"/>
<RowDefinition Height="3*"/>
<RowDefinition Height="1.5*"/>
</Grid.RowDefinitions>
<DataGrid x:Name="dgUser" IsReadOnly="True" AutoGenerateColumns="False" CanUserAddRows="False" HorizontalAlignment="Left" ItemsSource="{Binding UserList}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged" >
<i:InvokeCommandAction Command="{Binding SelectionCommand}" CommandParameter="{Binding ElementName=dgUser}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding ID}" Header="编号"/>
<DataGridTextColumn Binding="{Binding Name}" Header="姓名" Width="100"/>
<DataGridTextColumn Binding="{Binding Age}" Header="年龄"/>
<DataGridTextColumn Binding="{Binding Sex}" Header="性别" Width="60"/>
<DataGridTextColumn Binding="{Binding Address}" Header="地址" Width="172"/>
</DataGrid.Columns>
</DataGrid>
<GroupBox Header="用户基本信息" Grid.Row="1">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Grid.Column="0" Grid.Row="0" Orientation="Horizontal">
<Label x:Name="lblID" Content="编号:" VerticalAlignment="Center" />
<TextBox x:Name="tbxID" IsEnabled ="False" Text="{Binding SelectUser.ID}" VerticalAlignment="Center" MaxLength="5" Height="22" Width="90"/>
</StackPanel>
<StackPanel Grid.Column="1" Grid.Row="0" Orientation="Horizontal">
<Label x:Name="lblName" Content="姓名:" VerticalAlignment="Center" />
<TextBox x:Name="tbxName" Text="{Binding SelectUser.Name}" VerticalAlignment="Center" Height="22" MaxLength="6" Width="90"/>
</StackPanel>
<StackPanel Grid.Column="2" Grid.Row="0" Orientation="Horizontal">
<Label x:Name="lblAge" Content="年龄:" VerticalAlignment="Center" />
<TextBox x:Name="tbxAge" Text="{Binding SelectUser.Age}" VerticalAlignment="Center" Height="22" MaxLength="4" Width="90"/>
</StackPanel>
<StackPanel Grid.Column="0" Grid.Row="1" Orientation="Horizontal">
<Label x:Name="lblSex" Content="性别:" VerticalAlignment="Center"/>
<ComboBox Text="{Binding SelectUser.Sex}" SelectedIndex="0" x:Name="cbxSex" VerticalAlignment="Center" Width="90">
<ComboBoxItem Tag="1" Content="男"/>
<ComboBoxItem Tag="2" Content="女"/>
</ComboBox>
</StackPanel>
<StackPanel Grid.Column="1" Grid.ColumnSpan="2" Grid.Row="2" Orientation="Horizontal">
<Label x:Name="lblRemarks" Content="地址:" VerticalAlignment="Center"/>
<TextBox x:Name="tbxRemarks" Text="{Binding SelectUser.Address}" VerticalAlignment="Center" Height="22" Width="235" />
</StackPanel>
</Grid>
</GroupBox>
<GroupBox Header="功能操作" Grid.Row="2">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<Button x:Name="btnSave" Command="{Binding AddCommand}" Content="新增" VerticalAlignment="Center" Width="69" Height="19" Margin="10,0,10,0" />
<Button x:Name="btnUpdate" Command="{Binding UpdateCommand}" Content="修改" VerticalAlignment="Center" Width="69" Height="19" Margin="10,0,10,0"/>
<Button x:Name="btnDelete" Command="{Binding DeleteCommand}" Content="删除" VerticalAlignment="Center" Width="69" Height="19" Margin="10,0,10,0"/>
</StackPanel>
</GroupBox>
</Grid>
</Window>
如果你想点击表格内容,就能够在下方的用户基本信息刷新数据,那么你就需要引用:xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity",如果没有这个dll,请在【工具=》Nuget包管理器=》管理解决方案的Nuget程序包】中搜索System.Windows.Interactivity,选择【System.Windows.Interactivity.WPF】即可!
cs:
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new UserViewModel();
}
}
6.运行效果图:





若你们二位不幸看到我举例用户,找到我再说~~~~
7.项目源码:
百度网盘链接:https://pan.baidu.com/s/1fxsZAtfFURIJi-g2kqunjw 提取码:2zy4
优快云下载: https://download.youkuaiyun.com/download/dear200892/11827306