MVVM模式(C# WPF DataGrid实例)
学习资源:B站大佬–微软系列技术教程
视频链接:https://www.bilibili.com/video/BV1mJ411F7zG?p=9
大佬博客:https://www.cnblogs.com/zh7791/category/1122011.html?page=3
相关知识链接:微软文档对于RelayCommand的解析
本期学习笔记代码:https://www.aliyundrive.com/s/Vi1rHtLpwWD
推荐使用浏览器:必应(毕竟本来就是微软平台的)
本期是我对于学习了大佬对于MVVM模式的讲解和举例所得出的总结,如有侵权,可联系删除
MVVM模式框架解析图(针对本例)
案例解析
案例分为两个部分:1.Model和Db操作;2.Views和ViewModels;
Model和Db操作
- Model代码和解析
public class Student: ViewModelBase
{
private int id;
private string name;
public int Id
{
get { return id; }
set { id = value; RaisePropertyChanged(); }
}
public string Name
{
get { return name; }
set { name = value; RaisePropertyChanged(); }
}
}
- 数据库操作(这里并不是真正对数据库进行操作,只是简单的用了一个列表来替代)
public localDb()
{
init();
}
private List<Student> Studentls;
//初始化
private void init()
{
Studentls = new List<Student>();
for (int i = 0; i < 30; i++)
{
Studentls.Add(
new Student {
Id = i,
Name = $"Student{i}"
});
}
}
//查
public List<Student> GetStudents()
{
return Studentls;
}
//增
public bool AddStudents(Student stu)
{
Studentls.Add(stu);
return true;
}
//删除
public void DelStudent(int id)
{
var model = Studentls.FirstOrDefault(t => t.Id == id);
if (model != null)
{
Studentls.Remove(model);
}
}
//改
public bool EditStudent(Student stu)
{
Studentls[stu.Id] = stu;
return true;
}
//查
public List<Student> GetStudentsByName(string name)
{
return Studentls.Where(t => t.Name == name).ToList();
}
//查
public Student GetStudentById(int id)
{
return Studentls.FirstOrDefault(t => t.Id == id);
}
Views和ViewModels
Views指的就是UI,ViewModels指的是对于UI上的所有操作都通过Command寄存在ViewModels内部,分工合作;
Views只管UI层面的逻辑并且不涉及任何业务逻辑,通过Binding对应的Command指令名字即可引用;
ViewsModels:负责的就是UI层面的所有操作,包括业务逻辑(这里指的是对数据的操作),脏活累活都在这;
这里我尽贴出一处代码作为实例,剩余的可以查阅我写的代码(https://www.aliyundrive.com/s/Vi1rHtLpwWD)或是看一下视频内的代码;
- View
主界面Xaml代码块如下:
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding Id}"/>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
<DataGridTemplateColumn Header="Operation">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button Content="Edit" Width="60" Height="25" Background="White" Foreground="Black"
CommandParameter="{Binding Id}"
Command="{Binding DataContext.EditCommand, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGrid}}"
/>
<Button Content="Delete" Width="60" Height="25" Background="Red" Foreground="White" Margin="10 0 0 0"
CommandParameter="{Binding Id}"
Command="{Binding DataContext.DelCommand, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGrid}}"
/>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
需要注意的是一下几点:
1.绑定一般是通过括号+Binding,格式:{Binding Id},绑定名需要一一对应,这里的Id指的是Student(Model)构造的参数Id;
2.如果需要传入参数,需要引用CommandParameter参数,格式:CommandParameter="{Binding Id}";
主界面C#(View)代码如下:
public MainWindow()
{
MainViewModel mainViewModel = new MainViewModel();
InitializeComponent();
mainViewModel.initQuery();
this.DataContext = mainViewModel;//需要通过DataContext将上下文联系起来
}
UserView界面C#代码
public UserView(Student student)
{
InitializeComponent();
this.DataContext = new
{
Model = student
};
}
private void btnSave(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
}
private void btnCancel(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
}
- ViewModels
public MainViewModel()
{
localDb = new localDb();
DelCommand = new RelayCommand<int>(t => Del(t));
EditCommand = new RelayCommand<int>(t => Edit(t));
}
private void Del(int Id)
{
var model = localDb.GetStudentById(Id);
if (model != null)
{
var r = MessageBox.Show($"Could you Delect {model.Name}?", "Question", MessageBoxButton.OK, MessageBoxImage.Question);
if (r == MessageBoxResult.OK)
{
localDb.DelStudent(model.Id);
this.initQuery();//更新
}
}
}
private void Edit(int id)
{
Student stu = localDb.GetStudentById(id);
UserView userView = new UserView(stu);
var r = userView.ShowDialog();
if (r.Value)
{
localDb.EditStudent(stu);
this.initQuery();
}
}
public RelayCommand<int> DelCommand { get; set; }
public RelayCommand<int> EditCommand { get; set; }
EditStudent函数
public bool EditStudent(Student stu)
{
Studentls[stu.Id] = stu;
return true;
}
需要注意一下几点:
1.需要传入参数和不需要传入参数的Command差别在:定义Command的格式不一样和Xaml需要定义CommandParameter;
2.视频中部分可以在ViewModels完成的功能就直接编写了,我这里把所有的对于数据的操作全部写在localDb里面,而在ViewModels这就直接调用了,我觉得这样可以让整个框架更清晰;
3.绑定的好处:UI层面的数据进行传递时,不需要通过编写函数或是全局变量进行传递,例如这里的EditStudent(stu)函数是直接引用了传入UserView的stu,绑定则是通过this.DataContext = new {Model = student};详情可见***“UserView界面C#代码”***
总结
这是我默写的第四遍就拿出来分享的学习笔记和代码,还是有很多零碎不懂的知识点,如果读者有自己的见解或是指出本章有误的地方,都欢迎再评论区留言
首尾呼应一下哈哈哈
学习资源:B站大佬–微软系列技术教程
视频链接:https://www.bilibili.com/video/BV1mJ411F7zG?p=9
大佬博客:https://www.cnblogs.com/zh7791/category/1122011.html?page=3
相关知识链接:微软文档对于RelayCommand的解析
本期学习笔记代码:https://www.aliyundrive.com/s/Vi1rHtLpwWD
推荐使用浏览器:必应(毕竟本来就是微软平台的)
本期是我对于学习了大佬对于MVVM模式的讲解和举例所得出的总结,如有侵权,可联系删除