WPF MVVM实现数据增删改查逻辑全流程详细解析demo

摘要:
接口概述Gitee地址:WPFMVVM:使用mvvm模拟来实现数据添加、删除、修改和查询(Gitee.com)此示例包括两个View接口:MainWindow。xaml数据列表接口和StudentView xaml数据添加和编辑接口此示例使用命令绑定MvvvmLightRelayCommand来模拟数据添加、删除、修改和查询,这适用于WPF介绍。阅读效果如下:程序代码结构:添加Nuget包引用以实现主程序接口xaml code<Window

界面总览

gitee 地址:WPFMVVM: 使用mvvm模拟实现数据增删改查 (gitee.com)

本例中包含两个View 界面:MainWindow.xaml 数据列表界面,StudentView.xaml数据新增编辑界面

本例使用了命令绑定MvvmLight RelayCommand模拟数据增删改查操作,适用于WPF入门阅读

效果如下:

 WPF MVVM实现数据增删改查逻辑全流程详细解析demo第1张

程序代码结构:

WPF MVVM实现数据增删改查逻辑全流程详细解析demo第2张

 添加Nuget包引用

 WPF MVVM实现数据增删改查逻辑全流程详细解析demo第3张

实现程序主界面xaml代码

WPF MVVM实现数据增删改查逻辑全流程详细解析demo第4张

<Window
    x:Class="WpfMvvm.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:local="clr-namespace:WpfMvvm"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    Width="800"
    Height="450"
    mc:Ignorable="d">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="60" />
            <RowDefinition />
        Grid.RowDefinitions>
        <StackPanel Grid.Row="0" Orientation="Horizontal">
            <TextBlock
                Margin="10,0,0,0"
                VerticalAlignment="Center"
                Text="搜索条件" />
            <TextBox
                x:Name="QueryBox"
                Width="200"
                Height="25"
                Margin="10,0,0,0"
                VerticalContentAlignment="Center"
                Text="{Binding Search}" />
            <Button
                x:Name="QuertyButton"
                Width="30"
                Margin="10,0,0,0"
                HorizontalAlignment="Center"
                VerticalAlignment="Center"
                Command="{Binding QueryCommand}"
                Content="查询" />
            <Button
                x:Name="ResetButton"
                Width="30"
                Margin="10,0,0,0"
                HorizontalAlignment="Center"
                VerticalAlignment="Center"
                Command="{Binding ResetCommand}"
                Content="重置" />
            <Button
                x:Name="AddButton"
                Width="30"
                Margin="10,0,0,0"
                HorizontalAlignment="Center"
                VerticalAlignment="Center"
                Command="{Binding AddCommand}"
                Content="新增" />
        StackPanel>
        <DataGrid
            Grid.Row="1"
            AutoGenerateColumns="False"
            CanUserAddRows="False"
            ColumnWidth="*"
            ItemsSource="{Binding Students}">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Id}" Header="序号" />
                <DataGridTextColumn Binding="{Binding Name}" Header="姓名" />
                <DataGridTemplateColumn Width="100" Header="操作">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <Button
                                    x:Name="gridEdit"
                                    Width="30"
                                    Height="20"
                                    Margin="10,0,0,0"
                                    Command="{Binding DataContext.EditCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}}"
                                    CommandParameter="{Binding Id}"
                                    Content="编辑" />
                                <Button
                                    x:Name="gridDele"
                                    Width="30"
                                    Height="20"
                                    Margin="10,0,0,0"
                                    Command="{Binding DataContext.DeleCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}}"
                                    CommandParameter="{Binding Id}"
                                    Content="删除" />
                            StackPanel>
                        DataTemplate>
                    DataGridTemplateColumn.CellTemplate>
                DataGridTemplateColumn>
            DataGrid.Columns>
        DataGrid>
    Grid>
Window>

在ViewModel文件夹中添加MainViewModel 

using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System.Collections.ObjectModel;
using WpfMvvm.DB;
using WpfMvvm.Models;
using WpfMvvm.View;
using System.Linq;
using System.Windows;

namespace WpfMvvm.ViewModel
{
    public class MainViewModel : ViewModelBase
    {
        LocalDb localDb;
        public MainViewModel()
        {
            localDb = new LocalDb();
            QueryCommand = new RelayCommand(Query);
            ResetCommand = new RelayCommand(Reset);
            AddCommand = new RelayCommand(Add);
            EditCommand = new RelayCommand<int>(Edit);
            DeleCommand = new RelayCommand<int>(Dele);
        }

        private void Dele(int id)
        {
            if (MessageBox.Show("确认删除?","提示",MessageBoxButton.YesNo, MessageBoxImage.Question)== MessageBoxResult.Yes)
            {
                this.localDb.DeleteStudent(id);
                this.Query();
            }
        }

        private void Edit(int id)
        {
            var student = this.localDb.GetStudentsID(id);
            StudentView studentView = new StudentView();
            studentView.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            studentView.SetStudent(student);
            var dialog = studentView.ShowDialog();
            if (dialog == true)
            {
                student = this.Students.FirstOrDefault(x => x.Id == student.Id);
                student.Name = studentView.GetStudent().Name;
            }
        }

        private void Add()
        {
            Student student = new Student();
            StudentView studentView = new StudentView();
            studentView.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            studentView.SetStudent(student);

            var dialog = studentView.ShowDialog();

            if (dialog == true)
            {
                student = studentView.GetStudent();
                student.Id = this.Students.Max(x => x.Id) + 1;
                localDb.AddStudent(student);
                this.Query();
            }
        }

        private void Reset()
        {
            Search = string.Empty;
            Query();
        }

        public void Query()
        {
            var qstudents = localDb.GetStudentsByName(Search);
            Students = new ObservableCollection();
            if (qstudents != null)
            {
                qstudents.ForEach(x => Students.Add(x));
            }
        }


        #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> DeleCommand { get; set; }
        #endregion

        private string search;
        public string Search
        {
            get => search; set
            {
                search = value;
                RaisePropertyChanged();
            }
        }

        private ObservableCollection students;

        public ObservableCollection Students
        {
            get => students;
            set
            {
                students = value;
                RaisePropertyChanged();
            }
        }
    }
}

 数据编辑界面StudentView.xaml

 WPF MVVM实现数据增删改查逻辑全流程详细解析demo第5张

WPF MVVM实现数据增删改查逻辑全流程详细解析demo第6张WPF MVVM实现数据增删改查逻辑全流程详细解析demo第7张
<Window
    x:Class="WpfMvvm.View.StudentView"
    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:local="clr-namespace:WpfMvvm.View"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    Width="300"
    Height="300"
    WindowStartupLocation="CenterScreen"
    mc:Ignorable="d">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="60" />
            <RowDefinition />
            <RowDefinition Height="60" />
        </Grid.RowDefinitions>
        <TextBlock
            Grid.Row="0"
            Margin="10,0,0,0"
            VerticalAlignment="Center"
            FontWeight="Bold"
            Text="学生信息编辑" />

        <StackPanel
            Grid.Row="1"
            HorizontalAlignment="Center"
            VerticalAlignment="Center"
            Orientation="Horizontal">
            <TextBlock Margin="0,0,10,0" Text="姓名" />
            <TextBox Width="100" Text="{Binding Student.Name}" />
        </StackPanel>
        <StackPanel
            Grid.Row="2"
            HorizontalAlignment="Right"
            Orientation="Horizontal">
            <Button
                Width="30"
                Height="22"
                Margin="0,0,10,0"
                Command="{Binding ApplyCommand}"
                Content="确定" />
            <Button
                Width="30"
                Height="22"
                Margin="0,0,10,0"
                Command="{Binding CancleCommand}"
                Content="取消" />
        </StackPanel>
    </Grid>
</Window>
View Code

 StudentViewModel实现类

WPF MVVM实现数据增删改查逻辑全流程详细解析demo第8张WPF MVVM实现数据增删改查逻辑全流程详细解析demo第9张
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using WpfMvvm.Models;

namespace WpfMvvm.ViewModel
{
    public class StudentViewModel : ViewModelBase
    {
        public StudentViewModel()
        {
            ApplyCommand = new RelayCommand(Add);
            CancleCommand = new RelayCommand(Cancle);
        }
        /// <summary>
        /// 设置与view关联的窗体
        /// </summary>
        /// <param name="window"></param>
        public void SetWindow(Window window)
        {
            this.window = window;
        }

        private void Cancle()
        {
            this.window.Close();
        }

        private void Add()
        {
            this.window.DialogResult = true;

        }
        private Window window;
        private Student student;

        public Student Student
        {
            get => student;
            set
            {
                student = value;
                RaisePropertyChanged();
            }
        }

        #region Command
        public RelayCommand ApplyCommand { get; set; }
        public RelayCommand CancleCommand { get; set; }
        #endregion

    }
}
View Code
Student实体类
WPF MVVM实现数据增删改查逻辑全流程详细解析demo第10张WPF MVVM实现数据增删改查逻辑全流程详细解析demo第11张
using GalaSoft.MvvmLight;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfMvvm.Models
{
    public class Student : ViewModelBase
    {
        private int id;
        private string name;

        public int Id
        {
            get => id;
            set
            {
                id = value;
                RaisePropertyChanged(nameof(Id));
            }
        }
        public string Name
        {
            get => name; set
            {
                name = value;
                RaisePropertyChanged(nameof(Name));
            }
        }
    }
}
View Code

模拟数据库存储类LocalDb,实现数据增删改查

WPF MVVM实现数据增删改查逻辑全流程详细解析demo第12张WPF MVVM实现数据增删改查逻辑全流程详细解析demo第13张
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WpfMvvm.Models;

namespace WpfMvvm.DB
{
    public class LocalDb
    {
        public LocalDb()
        {
            Init();
          
        }

        public Student GetStudentsID(int id)
        {
            return students.FirstOrDefault(student => student.Id.Equals(id));
        }

        public List<Student> GetStudentsByName(string Name)
        {
            if (!string.IsNullOrEmpty(Name))
            {
                return students.Where(student=> student.Name.Contains(Name)).ToList();
            }
            return students;
        }

        private List<Student> students;
        private void Init()
        {
            students = new List<Student>();
            for (int i = 0; i < 30; i++)
            {
                students.Add(new Student { Id = i, Name = $"Name{i}" });
            }
        }

        public void DeleteStudent(int id)
        {
            var dele = this.students.FirstOrDefault(x => x.Id.Equals(id));
            if (dele != null)
            {
                this.students.Remove(dele);
            }
        }


        public void AddStudent(Student student)
        {
            this.students.Add(student);
        }

    }
}
View Code

View 与ViewModel 绑定处理

StudentView

 public partial class StudentView : Window
    {
        StudentViewModel viewModel;

        public StudentView()
        {
            InitializeComponent();
            viewModel = new StudentViewModel();
            this.DataContext = viewModel;
        }
       
        public void SetStudent(Student student)
        {
            viewModel.SetWindow(this);
            viewModel.Student = new Student { Id = student.Id, Name = student.Name };
        }

        public Student GetStudent()
        {
            return viewModel.Student;
        }
    }

MainWindow与MainViewModel

 public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            MainViewModel mainViewModel = new MainViewModel();
            mainViewModel.Query();
            this.DataContext = mainViewModel;
        }
    }

免责声明:文章转载自《WPF MVVM实现数据增删改查逻辑全流程详细解析demo》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇基于geowebcache切片服务的发布常见的几种数据加密与应用场景下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

kettle作业(job)调用转换,设置变量,写日志到数据库中【转】

首先建立转换:从数据库表到日志 表输入的设置:   日志设置:   新建job:     转换选择刚才建好的输出日志转换。变量设置如下: 此ID就是转换中的${ID},执行job,可以看到控制台输出日志结果:   黑色字体部分中只写出了id=1的一条记录。   最后补充,将转换的日志写到数据库中:打开转换>ctrl+t>日志选项...

数据分析之数据标准化

    数据标准化是一个常用的数据预处理操作,目的是处理不同规模和量纲的数据,使其缩放到相同的数据区间和范围,以减少规模、特征、分布差异等对模型的影响。除了用作模型计算,标准化的数据还具有直接计算并生成复合指标的意义,是加权指标的必要操作。 实现中心化和正态分布的Z-Score 转换公式: 其中x表示原数据,x' 表示转化后的数据,mean表示样本均值,...

学习WPF——WPF布局——了解布局容器

WPF布局工作内部原理 WPF渲染布局时主要执行了两个工作:测量和排列 测量阶段,容器遍历所有子元素,并询问子元素所期望的尺寸 排列阶段,容器在合适的位置放置子元素,并设置元素的最终尺寸 这是一个递归的过程,界面中任何一个容器元素都会被遍历到 WPF布局容器的继承机制 DispatcherObject WPF应用程序使用单线程亲和模型(STA...

WPF 下两种图片合成或加水印的方式

最近项目中应用多次应用了图片合成,为了今后方便特此记下。 在WPF下有两种图片合成的方式,一种还是用原来C#提供的GDI+方式,命名空间是System.Drawing 和 System.Drawing.Imaging,另一种是WPF中新添加的API,命名空间是 System.Windows.Media 和 System.Windows.Media.Imag...

在页面布局中,怎么实现水平居中和垂直居中?

先给出DOM结构 <div class="box"><div class="box-center"> </div> </div> 一:水平居中 若是行内元素,给其父元素设置text-align:center即可实现行内元素水平居中 若是块级元素,该元素设置margin:0 auto即可(元素需要定宽...

WPF基础知识、界面布局及控件Binding

  WPF是和WinForm对应的,而其核心是数据驱动事件,在开发中显示的是UI界面和逻辑关系相分离的一种开放语言。UI界面是在XAML语言环境下开发人员可以进行一些自主设计的前台界面,逻辑关系还是基于c#语言进行的逻辑设计。在使用WPF做项目的时候,免不了要对界面进行布局,同时需要对其中的控件进行绑定,本文主要是对这几方面进行介绍。 首先介绍WPF的基础...