WPF-DataGrid的增刪查改

背景:該功能為幾乎所有系統開發都需要使用的功能,現提供簡單的案例。

1、MyCommand

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;namespace WpfApplication25_DataGrid.ViewModels
{public class MyCommand:ICommand{private readonly Action _execute;private readonly Func<bool> _canExecute;private readonly Action<object> _execute2;public MyCommand(Action execute, Func<bool> canExecute = null){_execute = execute;// throw new ArgumentNullException(nameof(execute));_canExecute = canExecute;}public event EventHandler CanExecuteChanged{add { CommandManager.RequerySuggested += value; }remove { CommandManager.RequerySuggested -= value; }}public bool CanExecute(object parameter){return _canExecute == null || _canExecute();}public void Execute(object parameter){_execute();}}
}

2、Notify

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;namespace WpfApplication25_DataGrid.ViewModels
{public abstract class Notify : INotifyPropertyChanged{public event PropertyChangedEventHandler PropertyChanged;public void OnPropertyChanged([CallerMemberName] string name = null){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));}}
}

3、數據模型Person

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace WpfApplication25_DataGrid.Models
{public class Person{public int Id { get; set; }public string Name { get; set; }public int Age { get; set; }}
}

4、編輯EditPersonWindow.xaml

<Window x:Class="WpfApplication25_DataGrid.Views.EditPersonWindow"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:WpfApplication25_DataGrid.Views"mc:Ignorable="d"Title="EditPersonWindow" Height="200" Width="300"><Grid><StackPanel Orientation="Vertical" Margin="10"><Label Content="姓名:"/><TextBox Text="{Binding Person.Name}" Width="200"/><Label Content="年齡:"/><TextBox Text="{Binding Person.Age}" Width="200"/><StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,10,0,0"><Button Content="保存" Command="{Binding SaveCommand}" Width="80"/><Button Content="取消" Command="{Binding CancelCommand}" Width="80"/></StackPanel></StackPanel></Grid>
</Window>

5、編輯EditPersonWindow.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WpfApplication25_DataGrid.ViewModels;namespace WpfApplication25_DataGrid.Views
{/// <summary>/// EditPersonWindow.xaml 的交互邏輯/// </summary>public partial class EditPersonWindow : Window{public EditPersonWindow(EditPersonViewModel viewModel){InitializeComponent();this.DataContext = viewModel;}}
}

6、EditPersonViewModel.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using WpfApplication25_DataGrid.Models;namespace WpfApplication25_DataGrid.ViewModels
{public class EditPersonViewModel : Notify{public Person Person { get; set; }public Action<bool?> CloseAction { get; set; }public MyCommand SaveCommand { get; set; }public MyCommand CancelCommand { get; set; }public EditPersonViewModel(Person person){Person = person;SaveCommand = new MyCommand(SavePerson);CancelCommand = new MyCommand(Cancel);}private void SavePerson(){CloseAction?.Invoke(true);}private void Cancel(){CloseAction?.Invoke(false);}}
}

7、MainWindow.xaml

<Window x:Class="WpfApplication25_DataGrid.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:WpfApplication25_DataGrid"xmlns:vm="clr-namespace:WpfApplication25_DataGrid.ViewModels"mc:Ignorable="d"Title="MainWindow" Height="350" Width="525"><Grid><DataGrid ItemsSource="{Binding Persons}"SelectedItem="{Binding SelectedPerson}"AutoGenerateColumns="False"HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Height="200" Width="507"><DataGrid.Columns><DataGridTextColumn Header="ID" Binding="{Binding Id}" /><DataGridTextColumn Header="姓名" Binding="{Binding Name}" /><DataGridTextColumn Header="年齡" Binding="{Binding Age}" /></DataGrid.Columns></DataGrid><StackPanel Orientation="Horizontal" HorizontalAlignment="Left" Margin="10,220,0,0" VerticalAlignment="Top"><Button Content="新增" Command="{Binding AddCommand}" Width="80"/><Button Content="刪除" Command="{Binding DeleteCommand}" Width="80"/><Button Content="修改" Command="{Binding UpdateCommand}" Width="80"/><Button Content="搜索" Command="{Binding SearchCommand}" Width="80"/><TextBox Text="{Binding SelectTxt}" Width="100" Margin="10,0,0,0"HorizontalAlignment="Left" VerticalAlignment="Center"/></StackPanel></Grid>
</Window>

8.PersonViewModel.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;using WpfApplication25_DataGrid.Models;
using WpfApplication25_DataGrid.Views;namespace WpfApplication25_DataGrid.ViewModels
{public class PersonViewModel : Notify{public ObservableCollection<Person> Persons { get; set; }public Person SelectedPerson { get; set; }public ICommand AddCommand { get; set; }public ICommand DeleteCommand { get; set; }public ICommand UpdateCommand { get; set; }public ICommand SearchCommand { get; set; }/// <summary>/// 查詢字段/// </summary>private string selectTxt = "未登錄";public string SelectTxt{get { return selectTxt; }set{selectTxt = value;OnPropertyChanged();}}public PersonViewModel(){Persons = new ObservableCollection<Person>{new Person { Id = 1, Name = "Alice", Age = 25 },new Person { Id = 2, Name = "Bob", Age = 30 },new Person { Id = 3, Name = "Charlie", Age = 35 }};AddCommand = new MyCommand(AddPerson);DeleteCommand = new MyCommand(DeletePerson);UpdateCommand = new MyCommand(UpdatePerson);SearchCommand = new MyCommand(SearchPerson);}/// <summary>/// 增/// </summary>/// <param name="parameter"></param>private void AddPerson(){var newPerson = new Person();var editViewModel = new EditPersonViewModel(newPerson);var editWindow = new EditPersonWindow(editViewModel);editViewModel.CloseAction = (result) =>{editWindow.DialogResult = result;editWindow.Close();};if (editWindow.ShowDialog() == true){newPerson.Id = Persons.Count + 1;Persons.Add(newPerson);}}/// <summary>/// 刪/// </summary>/// <param name="parameter"></param>/// <returns></returns>private bool CanDeletePerson(){return SelectedPerson != null;}/// <summary>/// 刪除/// </summary>/// <param name="parameter"></param>private void DeletePerson(){if (SelectedPerson != null){var result = MessageBox.Show($"確認要刪除 {SelectedPerson.Name} 嗎?", "刪除確認", MessageBoxButton.YesNo);if (result == MessageBoxResult.Yes){Persons.Remove(SelectedPerson);}}}/// <summary>/// 更新/// </summary>/// <param name="parameter"></param>private void UpdatePerson(){if (SelectedPerson != null){var editViewModel = new EditPersonViewModel(SelectedPerson);var editWindow = new EditPersonWindow(editViewModel);editViewModel.CloseAction = (result) =>{editWindow.DialogResult = result;editWindow.Close();};if (editWindow.ShowDialog() == true){// 因為傳遞的是引用,修改已在窗口中完成}}}查詢private void SearchPerson(){string sss = SelectTxt;if (sss!=""){var searchResult = new ObservableCollection<Person>();foreach (var person in Persons){if (person.Id==Convert.ToInt16(sss)){searchResult.Add(person);}}Persons = searchResult;OnPropertyChanged(nameof(Persons));}}}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/71990.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/71990.shtml
英文地址,請注明出處:http://en.pswp.cn/web/71990.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Oracle數據庫存儲結構--物理存儲結構

數據庫存儲結構&#xff1a;分為物理存儲結構和邏輯存儲結構。 物理存儲結構&#xff1a;操作系統層面如何組織和管理數據 邏輯存儲結構&#xff1a;Oracle數據庫內部數據組織和管理數據&#xff0c;數據庫管理系統層面如何組織和管理數據 存儲結構 在Oracle數據庫的存儲結構…

歌詞相關實現

歌詞相關 歌詞數據模型&#xff1a; // Lyric.swift class Lyric: BaseModel {/// 是否是精確到字的歌詞var isAccurate:Bool false/// 所有的歌詞var datum:Array<LyricLine>! }// LyricLine.swift class LyricLine: BaseModel {/// 整行歌詞var data:String!/// 開始…

紡織服裝制造行業現狀 內檢實驗室系統在紡織服裝制造行業的應用

在紡織服裝制造行業&#xff0c;內檢實驗室LIMS系統&#xff08;實驗室信息管理系統&#xff09;已成為提升檢測效率、優化質量控制和滿足行業合規性要求的關鍵工具。隨著行業競爭的加劇和消費者對產品質量要求的提高&#xff0c;紡織服裝制造企業需要更加高效、準確的檢測流程…

K8s 1.27.1 實戰系列(十一)ConfigMap

ConfigMap 是 Kubernetes 中管理非敏感配置的核心資源,通過解耦應用與配置實現靈活性和可維護性。 一、ConfigMap 的核心功能及優勢 ?1、配置解耦 將配置文件(如數據庫地址、日志級別)與容器鏡像分離,支持動態更新而無需重建鏡像。 ?2、多形式注入 ?環境變量:將鍵值…

3分鐘復現 Manus 超強開源項目 OpenManus

文章目錄 前言什么是 OpenManus構建方式環境準備克隆代碼倉庫安裝依賴配置 LLM API運行 OpenManus 效果演示總結個人簡介 前言 近期人工智能領域迎來了一位備受矚目的新星——Manus。Manus 能夠獨立執行復雜的現實任務&#xff0c;無需人工干預。由于限制原因大部分人無法體驗…

從零開始學機器學習——構建一個推薦web應用

首先給大家介紹一個很好用的學習地址:https://cloudstudio.net/columns 今天,我們終于將分類器這一章節學習完活了,和回歸一樣,最后一章節用來構建web應用程序,我們會回顧之前所學的知識點,并新增一個web應用用來讓模型和用戶交互。所以今天的主題是美食推薦。 美食推薦…

【最后203篇系列】014 AI機器人-1

說明 終于開張了&#xff0c;我覺得AI機器人是一件真正正確&#xff0c;具有商業價值的事。 把AI機器人當成一筆生意&#xff0c;我如何做好這筆生意&#xff1f;一端是業務價值&#xff0c;另一端是技術支撐。如何構造高質量的內容和服務&#xff0c;如何確保技術的廣度和深度…

【大模型統一集成項目】如何封裝多個大模型 API 調用

&#x1f31f; 在這系列文章中&#xff0c;我們將一起探索如何搭建一個支持大模型集成項目 NexLM 的開發過程&#xff0c;從 架構設計 到 代碼實戰&#xff0c;逐步搭建一個支持 多種大模型&#xff08;GPT-4、DeepSeek 等&#xff09; 的 一站式大模型集成與管理平臺&#xff…

AI4CODE】3 Trae 錘一個貪吃蛇的小游戲

【AI4CODE】目錄 【AI4CODE】1 Trae CN 錐安裝配置與遷移 【AI4CODE】2 Trae 錘一個 To-Do-List 這次還是采用 HTML/CSS/JAVASCRIPT 技術棧 Trae 錘一個貪吃蛇的小游戲。 1 環境準備 創建一個 Snake 的子文件夾&#xff0c;清除以前的會話記錄。 2 開始構建 2.1 輸入會…

【簡答題002】Java變量簡答題

博主會經常補充完善這里面問題的答案。希望可以得到大家的一鍵三連支持&#xff0c;你的鼓勵是我堅持下去的最大動力&#xff01;謝謝&#xff01; 001 什么是Java變量&#xff1f; Java變量是用來存儲數據并在程序中引用的命名空間。 002 Java變量有哪些類型&#xff1f; J…

從零開發Chrome廣告攔截插件:開發、打包到發布全攻略

從零開發Chrome廣告攔截插件&#xff1a;開發、打包到發布全攻略 想打造一個屬于自己的Chrome插件&#xff0c;既能攔截煩人的廣告&#xff0c;又能優雅地發布到Chrome Web Store&#xff1f;別擔心&#xff0c;這篇教程將帶你從零開始&#xff0c;動手開發一個功能強大且美觀…

基于騰訊云高性能HAI-CPU的跨境電商客服助手全鏈路解析

跨境電商的背景以及痛點 根據Statista數據&#xff0c;2025年全球跨境電商市場規模預計達6.57萬億美元&#xff0c;年增長率保持在12.5% 。隨著平臺規則趨嚴&#xff08;如亞馬遜封店潮&#xff09;&#xff0c;更多賣家選擇自建獨立站&#xff0c;2024年獨立站占比已達35%。A…

maven的項目構建

常用構建命令 命令說明mvn clean清理編譯結果&#xff08;刪掉target目錄&#xff09;mvn compile編譯核心代碼&#xff0c;生成target目錄mvn test-compile編譯測試代碼&#xff0c;生成target目錄mvn test執行測試方法mvn package打包&#xff0c;生成jar或war文件mvn insta…

定時任務和分布式任務框架

文章目錄 一 Spring Task1.@Scheduled注解介紹2 基本用法(1)使用@EnableScheduling修飾啟動類(2)創建定時任務的類(3)fixedDelay(4)fixedRate(5)cron3 執行多個任務4 設置異步執行5 @Async使用自定義線程池6 缺點二 xxl-job介紹架構圖與其他任務調度平臺的比較運行調…

git安裝,配置SSH公鑰(查看版本、安裝路徑,更新版本)git常用指令

目錄 一、git下載安裝 1、下載git 2、安裝Git?&#xff1a; 二、配置SSH公鑰 三、查看安裝路徑、查看版本、更新版本 四、git常用指令 1、倉庫初始化與管理 2、配置 3、工作區與暫存區管理 4、提交 5、分支管理 6、遠程倉庫管理 7、版本控制 8、其他高級操作 一…

[Web]ServletContext域(Application)

簡介 Web應用的Application域的實現是通過ServletContext對象實現的。整個Web應用程序的所有資源共享這個域。生命周期與Web應用程序相同&#xff0c;即當前Web應用程序啟動時&#xff08;以服務器視角而非訪客視角&#xff09;出生&#xff0c;Web應用服務程序關閉時停止。 通…

qt c++ 進程和線程

在Qt C開發中&#xff0c;進程&#xff08;Process&#xff09;和線程&#xff08;Thread&#xff09;是兩種不同的并發模型&#xff0c;各有適用場景和實現方式。以下是詳細對比和實際開發中的用法總結&#xff1a; 一、進程&#xff08;Process&#xff09; 進程是操作系統資…

【鴻蒙開發】OpenHarmony調測工具hdc使用教程(設備開發者)

00. 目錄 文章目錄 00. 目錄01. OpenHarmony概述02. hdc簡介03. hdc獲取04. option相關的命令05. 查詢設備列表的命令06. 服務進程相關命令07. 網絡相關的命令08. 文件相關的命令09. 應用相關的命令10. 調試相關的命令11. 常見問題12. 附錄 01. OpenHarmony概述 OpenHarmony是…

手寫簡易Tomcat核心實現:深入理解Servlet容器原理

目錄 一、Tomcat概況 1. tomcat全局圖 2.項目結構概覽 二、實現步驟詳解 2.1 基礎工具包&#xff08;com.qcby.util&#xff09; 2.1.1 ResponseUtil&#xff1a;HTTP響應生成工具 2.1.2 SearchClassUtil&#xff1a;類掃描工具 2.1.3 WebServlet&#xff1a;自定義注解…

【Java開發指南 | 第三十四篇】IDEA沒有Java Enterprise——解決方法

讀者可訂閱專欄&#xff1a;Java開發指南 |【CSDN秋說】 文章目錄 1、新建Java項目2、單擊項目名&#xff0c;并連續按兩次shift鍵3、在搜索欄搜索"添加框架支持"4、勾選Web應用程序5、最終界面6、添加Tomcat 1、新建Java項目 2、單擊項目名&#xff0c;并連續按兩次…