DataGrid CRUD(MVVM模式)
引用程序包:MvvmLight
实体类:
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 Student Clone() { return this.MemberwiseClone() as Student; } }
数据库类:
public class StudentDb { public StudentDb() { Init(); } private List<Student> m_Students = new List<Student>(); private void Init() { for (int i = 0; i < 30; i++) { m_Students.Add(new Student() { Id = i, Name = $"姓名{i}" }); } } public List<Student> GetStudents() { return m_Students; } public void AddStudent(Student student) { m_Students.Add(student); } public void DelStudent(int id) { var model=m_Students.FirstOrDefault(x => x.Id == id); if (model != null) { m_Students.Remove(model); } } public List<Student> GetStudentByName(string name) { if(string.IsNullOrEmpty(name)) { return m_Students; } return m_Students.Where(m=>m.Name.Contains(name)).ToList(); } public int GetId() { return m_Students.Max(m => m.Id) + 1; } public Student? GetModel(int id) { return m_Students.FirstOrDefault(m => m.Id == id).Clone(); } }
ViewModel类
public class MainViewModel : ViewModelBase { StudentDb db; private ObservableCollection<Student> gridModelList; private string search; public MainViewModel() { db = new StudentDb(); QueryCommand = new RelayCommand(Query); ResetCommand = new RelayCommand(Reset); AddCommand = new RelayCommand(Add); EditCommand = new RelayCommand<int>(Edit); DeleteCommand = new RelayCommand<int>(m => Delete(m)); } public ObservableCollection<Student> GridModelList { get { return gridModelList; } set { gridModelList = value; RaisePropertyChanged(); } } //搜索条件 public string Search { get { return search; } set { search = value; RaisePropertyChanged(); } } public void Query() { GridModelList = new ObservableCollection<Student>(); var models = db.GetStudentByName(search); if (models != null) { models.ForEach(m => GridModelList.Add(m)); } } public void Reset() { Search = string.Empty; Query(); } public void Add() { Student student = new Student(); StudentEdit view = new StudentEdit(student); var result = view.ShowDialog(); if (result.HasValue && result.Value) { student.Id = db.GetId(); db.AddStudent(student); gridModelList.Add(student); } } public void Edit(int id) { var model = db.GetModel(id); if (model != null) { StudentEdit view = new StudentEdit(model); var result = view.ShowDialog(); if (result.HasValue && result.Value) { var oldModel = GridModelList.FirstOrDefault(m => m.Id == id); if (oldModel != null) { oldModel.Name = model.Name; } } } } public void Delete(int id) { var model = db.GetModel(id); if (model != null) { var result = MessageBox.Show($"是否删除当前行学生:{model.Name}?", "删除", MessageBoxButton.OKCancel, MessageBoxImage.Question); if (result == MessageBoxResult.OK) { db.DelStudent(id); var oldModel = GridModelList.FirstOrDefault(m => m.Id == id); if (oldModel != null) { GridModelList.Remove(oldModel); } } } } #region Command public RelayCommand QueryCommand { get; set; } public RelayCommand ResetCommand { get; set; } public RelayCommand AddCommand { get; set; } public RelayCommand<int> EditCommand { get; set; } public RelayCommand<int> DeleteCommand { get; set; } #endregion }
主窗口XML
<Window x:Class="WpfApp1.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:WpfApp1" mc:Ignorable="d" Title="MainWindow" Height="450" Width="820" Loaded="Window_Loaded" > <Grid Margin="5"> <Grid.RowDefinitions> <RowDefinition Height="60"></RowDefinition> <RowDefinition></RowDefinition> </Grid.RowDefinitions> <StackPanel Orientation="Horizontal"> <TextBlock Text="搜索条件:" VerticalAlignment="Center"/> <TextBox Text="{Binding Search}" Width="200" Height="25" Margin="10,0,0,0"/> <Button Content="查找" Command="{Binding QueryCommand}" Width="70" Height="25" Margin="10,0,0,0"/> <Button Content="重置" Command="{Binding ResetCommand}" Width="70" Height="25" Margin="10,0,0,0"/> <Button Content="新增" Command="{Binding AddCommand}" Width="70" Height="25" Margin="10,0,0,0"/> </StackPanel> <DataGrid Grid.Row="1" ColumnWidth="*" AutoGenerateColumns="False" CanUserAddRows="False" ItemsSource="{Binding GridModelList}"> <DataGrid.Columns> <DataGridTextColumn Header="序号" Binding="{Binding Id}"/> <DataGridTextColumn Header="姓名" Binding="{Binding Name}"/> <DataGridTemplateColumn Header="操作"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <Button Content="修改" CommandParameter="{Binding Id}" Command="{Binding DataContext.EditCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGrid}}" Width="60" Height="25" Background="White" Foreground="Black"/> <Button Content="删除" CommandParameter="{Binding Id}" Command="{Binding DataContext.DeleteCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGrid}}" Width="60" Height="25" Background="Red" Foreground="White"/> </StackPanel> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> </Grid> </Window>
主窗口后台文件
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { MainViewModel viewModel=new MainViewModel(); viewModel.Query(); this.DataContext = viewModel; } }
编辑窗口XML
<Window x:Class="WpfApp1.Views.StudentEdit" 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:WpfApp1.Views" mc:Ignorable="d" Title="StudentEdit" Height="350" Width="400" WindowStyle="None" AllowsTransparency="False" WindowStartupLocation="CenterScreen"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="60"></RowDefinition> <RowDefinition></RowDefinition> <RowDefinition Height="60"></RowDefinition> </Grid.RowDefinitions> <TextBlock Text="编辑学习信息" FontWeight="Bold" FontSize="30" Margin="10,0,0,0" VerticalAlignment="Center"/> <StackPanel Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center"> <TextBlock Text="姓名:" VerticalAlignment="Center"/> <TextBox Text="{Binding Model.Name}" Width="200" Height="25"/> </StackPanel> <StackPanel Orientation="Horizontal" Grid.Row="2" HorizontalAlignment="Right"> <Button x:Name="ok" Width="70" Height="25" Content="确定" Click="ok_Click"/> <Button x:Name="cancel" Width="70" Height="25" Content="取消" Click="cancel_Click" Margin="10,0,10,0"/> </StackPanel> </Grid> </Window>
编辑窗口后台
public partial class StudentEdit : Window { public StudentEdit(Student student) { InitializeComponent(); this.DataContext=new {Model= student}; } private void ok_Click(object sender, RoutedEventArgs e) { this.DialogResult = true; this.Close(); } private void cancel_Click(object sender, RoutedEventArgs e) { this.DialogResult = false; this.Close(); } }