WPF-21 基于MVVM员工管理-01

接下来我们通过两节课程使用MVVM来开发一个简单的Demo,首先我们创建一个项目名称WPF-22-MVVM-Demo,目录结构如下:

c64ac657c44fa3ea7c18879af220fe0d.png

我们在Models文件下创建Employee类并让该类实现INotifyPropertyChanged接口,该类中定义编号、姓名和角色三个基本属性

using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace WPF_22_MVVM_Demo.Models
{public class Employee : INotifyPropertyChanged{private string no = String.Empty;public string No{get{return no;}set{if (value != this.no){no = value;NotifyPropertyChanged();}}}private string name = String.Empty;public string Name{get{return name;}set{if (value != this.name){this.name = value;NotifyPropertyChanged();}}}private string role = String.Empty;public string Role{get{return role;}set{if (value != this.role){this.role = value;NotifyPropertyChanged();}}}public event PropertyChangedEventHandler? PropertyChanged;private void NotifyPropertyChanged([CallerMemberName] String propertyName = ""){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}}
}

在Models文件下定义服务EmployeeService,该类可以包含一些常用业务操作,例如:对远程api调用操作远程数据库以及本地数据库操作等,在该例子中,我们对一个内存对象集合实现增删改查操作

using System.Collections.Generic;
using System.Linq;
namespace WPF_22_MVVM_Demo.Models
{public class EmployeeService{private static List<Employee> _employees = null!;public EmployeeService(){_employees = new List<Employee>(){new Employee(){No="800001",Name="张三丰",Role="武当派掌门人"},new Employee(){No="800002",Name="乔峰",Role="乞丐掌门人"},};}public List<Employee> GetEmployees(){return _employees;}}
}

在Commands文件夹下定义DelegateCommand

using System;
using System.Windows.Input;
namespace WPF_22_MVVM_Demo.Commands
{public class DelegateCommand : ICommand{private Action _execute;private Func<bool> _canExecute;public DelegateCommand(Action executeMethod){_execute = executeMethod;}public DelegateCommand(Action executeMethod, Func<bool> canExecute): this(executeMethod){this._canExecute = canExecute;}public event EventHandler CanExecuteChanged;public bool CanExecute(object parameter){return true;}       public void Execute(object parameter){_execute();}}
}

在ViewModes文件加下创建EmployeeViewMode,同时该类实现INotifyPropertyChanged接口,该类引用了Employee 实体(用来绑定到UI页面)和EmployeeService服务以及DelegateCommand 类

using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Input;
using WPF_22_MVVM_Demo.Commands;
using WPF_22_MVVM_Demo.Models;
namespace WPF_22_MVVM_Demo.ViewModes
{public class EmployeeViewMode : INotifyPropertyChanged{public event PropertyChangedEventHandler? PropertyChanged;private void NotifyPropertyChanged([CallerMemberName] String propertyName = ""){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}EmployeeService employeeService;public EmployeeViewMode(){employeeService = new EmployeeService();BindData();Employee = new Employee();}private Employee employee;public Employee Employee{get { return employee; }set { employee = value;NotifyPropertyChanged(); }}private ObservableCollection<Employee> employeeList;public ObservableCollection<Employee> EmployeeList{get{return employeeList;}set{employeeList = value;NotifyPropertyChanged();}}/// <summary>///消息提示/// </summary>public string Message{get;set;}/// <summary>/// DataGrid绑定数据/// </summary>public void BindData(){EmployeeList = new ObservableCollection<Employee>(employeeService.GetEmployees());} }
}

在Views文件加下创建EmployeeView.xaml,将窗体的DataContext指向EmployeeViewMode,在该界面有两部分组成:

  1. 录入信息,将文本框和EmployeeViewMode中的Employee对象的属性做绑定

  2. DataGrid展示数据列表,将控件的ItemsSource属性绑定EmployeeViewMode对象中的EmployeeList属性

<UserControl x:Class="WPF_22_MVVM_Demo.Views.EmployeeView"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d"><Grid><Grid.RowDefinitions><RowDefinition Height="0.1*"></RowDefinition><RowDefinition Height="0.1*"></RowDefinition><RowDefinition Height="0.1*"></RowDefinition><RowDefinition Height="0.1*"></RowDefinition><RowDefinition Height="0.6*"></RowDefinition></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition Width="0.35*"></ColumnDefinition><ColumnDefinition Width="0.65*"></ColumnDefinition></Grid.ColumnDefinitions><TextBlock Grid.Row="0" Grid.Column="0" Margin="10">员工编号</TextBlock><TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Path=Employee.No}" Width="150" HorizontalAlignment="Left" Margin="10"/><TextBlock Grid.Row="1" Grid.Column="0" Margin="10">员工姓名</TextBlock><TextBox Grid.Row="1" Grid.Column="1" Text="{Binding Path=Employee.Name}" Width="150" HorizontalAlignment="Left" Margin="10"></TextBox><TextBlock Grid.Row="2" Grid.Column="0" Margin="10">角色</TextBlock><TextBox Grid.Row="2" Grid.Column="1" Text="{Binding Path=Employee.Role}" Width="150" HorizontalAlignment="Left" Margin="10"></TextBox><StackPanel Grid.Row="3" Grid.ColumnSpan="2" Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Top"><Grid><Grid.RowDefinitions><RowDefinition></RowDefinition></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition></ColumnDefinition><ColumnDefinition></ColumnDefinition><ColumnDefinition></ColumnDefinition><ColumnDefinition></ColumnDefinition></Grid.ColumnDefinitions></Grid><Button Content="新增" Width="100" Height="30" Margin="2"></Button><Button Content="修改" Width="100" Height="30" Margin="2"></Button><Button Content="删除" Width="100" Height="30" Margin="2"></Button><Button Content="查询" Width="100" Height="30" Margin="2"></Button></StackPanel><DataGrid Grid.Row="4" Grid.ColumnSpan="2" Name="empGrid" AutoGenerateColumns="False" ItemsSource="{Binding Path=EmployeeList,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"><DataGrid.Columns><DataGridTextColumn Header="员工编号" Width="0.3*" Binding="{Binding Path=No,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></DataGridTextColumn><DataGridTextColumn Header="姓名" Width="0.3*" Binding="{Binding Path=Name,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></DataGridTextColumn><DataGridTextColumn Header="角色" Width="0.3*" Binding="{Binding Path=Role,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></DataGridTextColumn></DataGrid.Columns></DataGrid></Grid>
</UserControl>
using System.Windows.Controls;
using WPF_22_MVVM_Demo.ViewModes;
namespace WPF_22_MVVM_Demo.Views
{/// <summary>/// Interaction logic for EmployeeView.xaml/// </summary>public partial class EmployeeView : UserControl{public EmployeeView(){InitializeComponent();this.DataContext = new EmployeeViewMode();}}
}

在MainWindow.xaml窗体中引用EmployeeView

<Window x:Class="WPF_22_MVVM_Demo.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:EmpView="clr-namespace:WPF_22_MVVM_Demo.Views"mc:Ignorable="d"Title="员工管理" Height="450" Width="500"><StackPanel><EmpView:EmployeeView></EmpView:EmployeeView></StackPanel>
</Window>

运行如下:

8d2bd2a4223d526fb0a62df30876d418.png

这节我们主要介绍MVVM项目整体结构以及UI页面布局,并且将控件和ViewModel数据模型进行了绑定,实现了最基本DataGrid数据绑定,在接下来我们将实现增删改查

WPF中Command绑定引用了设计模式中的命令模式(Command Pattern)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/280013.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

qt 苹果应用程序_什么是苹果的电视应用程序,您应该使用它吗?

qt 苹果应用程序Apple’s TV app, which recently appeared on iOS devices and Apple TV, is meant to help users discover and watch shows across an increasingly expanding lineup of television channels, as well as iTunes movies and shows, in one central app. App…

细说flush、ob_flush的区别

ob_flush/flush在手册中的描述, 都是刷新输出缓冲区, 并且还需要配套使用, 所以会导致很多人迷惑… 其实, 他们俩的操作对象不同, 有些情况下, flush根本不做什么事情.. ob_*系列函数, 是操作PHP本身的输出缓冲区. 所以, ob_flush是刷新PHP自身的缓冲区. 而flush, 严格来讲, 这…

关于jHipster框架在构建中的出现的error修复

jhipster The JDL object and the database type are both mandatory.这个错误应该是在构建基于jHipster的spring-cloud项目中经常遇到的&#xff0c;因为这个在这个过程中会读取.yo-rc文件&#xff0c;之后生成相关的.json文件&#xff0c;再之后生成相关的.java文件&#xff…

定制.NET 6.0的Middleware中间件

大家好&#xff0c;我是张飞洪&#xff0c;感谢您的阅读&#xff0c;我会不定期和你分享学习心得&#xff0c;希望我的文章能成为你成长路上的垫脚石&#xff0c;让我们一起精进。在本文中&#xff0c;我们将学习中间件&#xff0c;以及如何使用它进一步定制应用程序。我们将快…

删除microsoft_如何从您的Microsoft帐户中删除设备

删除microsoftWhen you sign into Windows 8 or 10 using your Microsoft account (and other Microsoft devices, like an Xbox), those devices become associated with your account. If you want to remove an old device you’ve gotten rid of, you’ll have to pay a vi…

线程的语法 (event,重要)

Python threading模块 2种调用方式 直接调用 12345678910111213141516171819import threadingimport timedef sayhi(num): #定义每个线程要运行的函数print("running on number:%s" %num)time.sleep(3)if __name__ __main__:t1 threading.Thread(targetsayhi,args(…

求最大值和下标值

本题要求编写程序&#xff0c;找出给定的n个数中的最大值及其对应的最小下标&#xff08;下标从0开始&#xff09;。 输入格式: 输入在第一行中给出一个正整数n&#xff08;1<n≤10&#xff09;。第二行输入n个整数&#xff0c;用空格分开。 输出格式: 在一行中输出最大值及…

windows应用商店修复_如何修复Windows应用商店中的卡死下载

windows应用商店修复Though it’s had its share of flaky behavior since being introduced in Windows 8, the Windows Store has gotten more reliable over time. It still has the occasional problems, though. One of the more irritating issues is when an app update…

新冠病毒中招 | 第二天

今天跟大家分享我个人感染奥密克戎毒株第二天的经历和感受。早上7点多自然醒来&#xff0c;已经没有四肢乏力的感觉&#xff0c;但是身体的本能还是告诉我不愿意动弹。由于第一天躺着睡了一天&#xff0c;确实是躺得腰酸背疼的。起床量了一下体温36.4正常&#xff0c;决定今天不…

icloud 购买存储空间_如何释放iCloud存储空间

icloud 购买存储空间Apple offers 5 GB of free iCloud space to everyone, but you’ll run up against that storage limit sooner than you’d think. Device backups, photos, documents, iCloud email, and other bits of data all share that space. Apple为每个人提供5 …

基于LAMP实现web日志管理查看

前言&#xff1a;日志是一个重要的信息库&#xff0c;如何高效便捷的查看系统中的日志信息&#xff0c;是系统管理员管理系统的必备的技术。实现方式&#xff1a;1、将日志存储于数据库。2、采用LAMP架构&#xff0c;搭建PHP应用&#xff0c;通过web服务访问数据库&#xff0c;…

WPF效果第二百零七篇之EditableSlider

前面简单玩耍一下快速黑白灰效果; 今天又玩了一下ZoomBlurEffect,来看看最终实现的效果:1、ps和cs文件都在Shazzam中,咱们自己随意玩耍;今天主角是下面这位:2、来看看自定义控件布局(TextBox、Slider、ToggleButton)&#xff1a;3、点击编辑按钮,我就直接偷懒了:private void E…

使用MyQ打开车库门时如何接收警报

Chamberlain’s MyQ technology is great for opening and closing your garage door remotely with your smartphone, but you can also receive alerts whenever your garage door opens and closes (as well as receive alerts when it’s been open for an extended amount…

mac 防火墙禁止程序联网_如何允许应用程序通过Mac的防火墙进行通信

mac 防火墙禁止程序联网If you use a Mac, chances are you might not even realize that OS X comes with a firewall. This firewall helps ensure unauthorized app and services can’t contact your computer, and prevents intruders from sniffing out your Mac on a ne…

WPF-22 基于MVVM员工管理-02

我们接着上一节&#xff0c;这节我们实现crud操作&#xff0c;我们在EmployeeViewMode类中新增如下成员&#xff0c;并在构造函数中初始化该成员code snippetpublic EmployeeViewMode() {employeeService new EmployeeService();BindData();Employee new Employee();AddComma…

linux 3

-- Linux -- 开心的一天 vi   所有的 unix like 系统都会内置 vi 文本编辑器 vim  较多使用的,可以主动的以字体颜色辨别语法的正确性&#xff0c;方便程序设计 vi/vim 的使用 -- 命令模式&#xff08;Command mode&#xff09; 输入模式&#xff08;Insert mode&#x…

从零开始搭建一个简单的ui自动化测试框架02(pytest+selenium+allure)

二、先搭一个架子 在我还是小白连py语法都不太熟悉的时候&#xff0c;经常在网上看关于自学ui自动化测试的博客&#xff0c;最熟悉的套路莫过于先给你介绍一下selenium的各个api&#xff0c;然后写一套代码去登陆微博或者百度什么的&#xff0c;但我今天不愿意这么写&#xff0…

什么是Adobe Lightroom,我需要它吗?

Adobe Photoshop Lightroom confuses a lot of new photographers. It has Photoshop in the name, but it isn’t Photoshop? What gives? Adobe Photoshop Lightroom使许多新摄影师感到困惑。 它的名称是Photoshop&#xff0c;但不是Photoshop吗&#xff1f; 是什么赋予了&…

jquery中的serializeArray方法的使用

转载于:https://blog.51cto.com/11871779/2359556

机器学习(一)—— 线性回归

机器学习&#xff08;一&#xff09;—— 线性回归 目录 0. 回归&#xff08;Regression&#xff09;的由来 1. 回归关系 2. 线性回归的整体思路 &#xff08;1&#xff09;根据数据提出假设模型 &#xff08;2&#xff09;求解参数 1&#xff09;梯度下降法 2&#xff09;正规…