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.pswp.cn/news/280013.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/280013.shtml
英文地址,請注明出處:http://en.pswp.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…

protobuf編碼

proto2Protocol Buffers 是一種輕便高效的結構化數據存儲格式&#xff0c;可以用于結構化數據序列化&#xff0c;適合做數據存儲或 RPC 數據交換格式。可用于通訊協議、數據存儲等領域的語言無關、平臺無關、可擴展的序列化結構數據格式。 字段規則 required: 字段必須存在opti…

定制.NET 6.0的Middleware中間件

大家好&#xff0c;我是張飛洪&#xff0c;感謝您的閱讀&#xff0c;我會不定期和你分享學習心得&#xff0c;希望我的文章能成為你成長路上的墊腳石&#xff0c;讓我們一起精進。在本文中&#xff0c;我們將學習中間件&#xff0c;以及如何使用它進一步定制應用程序。我們將快…

Python-循環控制--個人課堂筆記

Python中的兩種循環方式&#xff08;目前學到&#xff09;&#xff1a;for循環和while循環 for循環和while循環的區別&#xff1a; for循環一般用于控制循環的次數&#xff0c;while循環則是條件循環。 操作實例-猜數字小游戲&#xff08;3次猜錯提示游戲結束&#xff09;&…

刪除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…

OpenWrt:Linux下生成banner

Linux下有三個小工具可以生成banner&#xff1a;1、banner使用#生成banner&#xff1b;2、figlet使用一些普通字符生成banner&#xff1b;3、toilet使用一些復雜的彩色特殊字符生成banner。使用apt-get安裝的時候需要輸入以下命令&#xff1a; $ sudo apt-get install sysvbann…

新冠病毒中招 | 第二天

今天跟大家分享我個人感染奧密克戎毒株第二天的經歷和感受。早上7點多自然醒來&#xff0c;已經沒有四肢乏力的感覺&#xff0c;但是身體的本能還是告訴我不愿意動彈。由于第一天躺著睡了一天&#xff0c;確實是躺得腰酸背疼的。起床量了一下體溫36.4正常&#xff0c;決定今天不…

輸出到Excel

HSSFWorkbook oBook new HSSFWorkbook(); NPOI.SS.UserModel.ISheet oSheet oBook.CreateSheet(); #region 輸出到Excel MemoryStream ms new MemoryStream(); oBook.Write(ms);string sExportPath ""; using (SaveFileDialog saveFileDialog1 new SaveFileDial…

JavaScript 精粹 基礎 進階(5)數組

轉載請注明出處 原文連接 blog.huanghanlian.com/article/5b6… 數組是值的有序集合。每個值叫做元素&#xff0c;每個元素在數組中都有數字位置編號&#xff0c;也就是索引。JS中的數組是弱類型的&#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…

閑話高并發的那些神話,看京東架構師如何把它拉下神壇

轉載:閑話高并發的那些神話&#xff0c;看京東架構師如何把它拉下神壇 高并發也算是這幾年的熱門詞匯了&#xff0c;尤其在互聯網圈&#xff0c;開口不聊個高并發問題&#xff0c;都不好意思出門。高并發有那么邪乎嗎&#xff1f;動不動就千萬并發、億級流量&#xff0c;聽上去…

c# Clone方法

clone是深拷貝&#xff0c;copy是淺拷貝&#xff0c;如果是值類型的話是沒什么區別的&#xff0c;如果是引用類型的話深拷貝拷貝的事整個對象的數據&#xff0c;而淺拷貝僅僅拷貝對象的引用。因為類的實例是引用類型&#xff0c;要想用原有的類中的實例的數據的話&#xff0c;既…

使用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…