C# WPF入門學習主線篇(十)—— DataGrid常見屬性和事件

C# WPF入門學習主線篇(十)—— DataGrid常見屬性和事件

歡迎來到C# WPF入門學習系列的第十篇。在前面的文章中,我們已經學習了 ButtonTextBoxLabelListBoxComboBox 控件。今天,我們將探討 WPF 中的另一個重要控件——DataGrid。本文將詳細介紹 DataGrid 的常見屬性和事件,并通過示例代碼展示其在實際應用中的使用。

一、DataGrid的基礎知識

DataGrid 是一個非常強大的控件,用于顯示和操作表格數據。它允許用戶以表格形式查看數據,并支持排序、分組、篩選、編輯等功能。

DataGrid的基本定義

我們先來看看一個簡單的 DataGrid 定義:

<Window x:Class="WpfApp.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"Title="MainWindow" Height="350" Width="525"><Grid><DataGrid x:Name="myDataGrid" AutoGenerateColumns="True" HorizontalAlignment="Left" VerticalAlignment="Top" Width="500" Height="300"/></Grid>
</Window>

在這個示例中,我們定義了一個 DataGrid 控件,并設置了 AutoGenerateColumns 屬性為 True,這意味著列將自動根據數據源生成。

二、DataGrid的常見屬性

1. ItemsSource

ItemsSource 屬性用于綁定 DataGrid 的數據源。可以是數組、列表或任何實現了 IEnumerable 接口的集合。

<DataGrid x:Name="myDataGrid" AutoGenerateColumns="True" HorizontalAlignment="Left" VerticalAlignment="Top" Width="500" Height="300"/>
public partial class MainWindow : Window
{public MainWindow(){InitializeComponent();myDataGrid.ItemsSource = new List<Person>{new Person { Name = "John Doe", Age = 30 },new Person { Name = "Jane Smith", Age = 25 }};}
}public class Person
{public string Name { get; set; }public int Age { get; set; }
}

在這里插入圖片描述

2. AutoGenerateColumns

AutoGenerateColumns 屬性決定是否自動生成列。設置為 False 時,需要手動定義列。

<DataGrid x:Name="myDataGrid" AutoGenerateColumns="False" HorizontalAlignment="Left" VerticalAlignment="Top" Width="500" Height="300"><DataGrid.Columns><DataGridTextColumn Header="Name" Binding="{Binding Name}"/><DataGridTextColumn Header="Age" Binding="{Binding Age}"/></DataGrid.Columns>
</DataGrid>

3. ColumnHeaderHeight

ColumnHeaderHeight 屬性設置列標題的高度。

<DataGrid x:Name="myDataGrid" ColumnHeaderHeight="40" AutoGenerateColumns="True" HorizontalAlignment="Left" VerticalAlignment="Top" Width="500" Height="300"/>

4. CanUserAddRows

CanUserAddRows 屬性設置用戶是否可以添加新行。

<DataGrid x:Name="myDataGrid" CanUserAddRows="False" AutoGenerateColumns="True" HorizontalAlignment="Left" VerticalAlignment="Top" Width="500" Height="300"/>

5. CanUserDeleteRows

CanUserDeleteRows 屬性設置用戶是否可以刪除行。

<DataGrid x:Name="myDataGrid" CanUserDeleteRows="False" AutoGenerateColumns="True" HorizontalAlignment="Left" VerticalAlignment="Top" Width="500" Height="300"/>

6. IsReadOnly

IsReadOnly 屬性設置 DataGrid 是否為只讀。

<DataGrid x:Name="myDataGrid" IsReadOnly="True" AutoGenerateColumns="True" HorizontalAlignment="Left" VerticalAlignment="Top" Width="500" Height="300"/>

示例

下面是一個包含以上常見屬性的完整示例:

<Window x:Class="WpfApp.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"Title="MainWindow" Height="350" Width="525"><Grid><DataGrid x:Name="myDataGrid" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="True" IsReadOnly="False"ColumnHeaderHeight="40" HorizontalAlignment="Left" VerticalAlignment="Top" Width="500" Height="300"><DataGrid.Columns><DataGridTextColumn Header="Name" Binding="{Binding Name}"/><DataGridTextColumn Header="Age" Binding="{Binding Age}"/></DataGrid.Columns></DataGrid></Grid>
</Window>
using System.Collections.Generic;
using System.Windows;namespace WpfApp
{public partial class MainWindow : Window{public MainWindow(){InitializeComponent();myDataGrid.ItemsSource = new List<Person>{new Person { Name = "John Doe", Age = 30 },new Person { Name = "Jane Smith", Age = 25 }};}}public class Person{public string Name { get; set; }public int Age { get; set; }}
}

三、DataGrid的常見事件

1. LoadingRow

LoadingRow 事件在行加載時觸發。

XAML代碼
<DataGrid x:Name="myDataGrid" AutoGenerateColumns="True" LoadingRow="MyDataGrid_LoadingRow" HorizontalAlignment="Left" VerticalAlignment="Top" Width="500" Height="300"/>
后臺代碼
private void MyDataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{e.Row.Header = (e.Row.GetIndex() + 1).ToString();
}

2. SelectionChanged

SelectionChanged 事件在選擇的項目發生更改時觸發。

XAML代碼
<DataGrid x:Name="myDataGrid" AutoGenerateColumns="True" SelectionChanged="MyDataGrid_SelectionChanged" HorizontalAlignment="Left" VerticalAlignment="Top" Width="500" Height="300"/>
后臺代碼
private void MyDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{DataGrid dataGrid = sender as DataGrid;Person selectedPerson = dataGrid.SelectedItem as Person;if (selectedPerson != null){MessageBox.Show($"Selected Person: {selectedPerson.Name}, Age: {selectedPerson.Age}");}
}

3. CellEditEnding

CellEditEnding 事件在單元格編輯即將結束時觸發。

XAML代碼
<DataGrid x:Name="myDataGrid" AutoGenerateColumns="True" CellEditEnding="MyDataGrid_CellEditEnding" HorizontalAlignment="Left" VerticalAlignment="Top" Width="500" Height="300"/>
后臺代碼
private void MyDataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{MessageBox.Show("Cell editing is ending.");
}

示例總結

以下是一個包含所有三種常見事件的完整示例:

<Window x:Class="WpfApp.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"Title="MainWindow" Height="350" Width="525"><!-- 定義一個 Grid 容器,用于布局子控件 --><Grid><!-- 定義一個 DataGrid 控件 --><DataGrid x:Name="myDataGrid"AutoGenerateColumns="True" <!-- 自動生成列 -->LoadingRow="MyDataGrid_LoadingRow" <!-- 行加載事件 -->SelectionChanged="MyDataGrid_SelectionChanged" <!-- 選擇更改事件 -->CellEditEnding="MyDataGrid_CellEditEnding" <!-- 單元格編輯結束事件 -->HorizontalAlignment="Left" VerticalAlignment="Top" <!-- 控件水平和垂直對齊 -->Width="500" Height="300"/> <!-- 控件寬度和高度 --></Grid>
</Window>
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;namespace WpfApp
{public partial class MainWindow : Window{public MainWindow(){InitializeComponent(); // 初始化組件// 初始化數據源并綁定到 DataGridmyDataGrid.ItemsSource = new List<Person>{new Person { Name = "John Doe", Age = 30 },new Person { Name = "Jane Smith", Age = 25 }};}// 行加載事件處理程序private void MyDataGrid_LoadingRow(object sender, DataGridRowEventArgs e){// 設置行頭為行索引加一(從1開始)e.Row.Header = (e.Row.GetIndex() + 1).ToString();}// 選擇更改事件處理程序private void MyDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e){// 獲取觸發事件的 DataGridDataGrid dataGrid = sender as DataGrid;// 獲取選中的項目并轉換為 Person 類型Person selectedPerson = dataGrid.SelectedItem as Person;if (selectedPerson != null) // 如果有選中的項目{// 顯示選中的人的名字和年齡MessageBox.Show($"Selected Person: {selectedPerson.Name}, Age: {selectedPerson.Age}");}}// 單元格編輯結束事件處理程序private void MyDataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e){// 顯示單元格編輯結束消息MessageBox.Show("Cell editing is ending.");}}// 定義一個簡單的 Person 類,用于數據綁定public class Person{public string Name { get; set; } // 名字屬性public int Age { get; set; } // 年齡屬性}
}

四、總結

本文詳細介紹了 WPF 中 DataGrid 控件的常見屬性和事件,通過具體的示例代碼展示了如何使用這些屬性和事件。通過本文的學習,讀者應該能夠掌握 DataGrid 的基本用法,并在實際項目中靈活運用這些知識。

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

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

相關文章

Python私教張大鵬 Vue3整合AntDesignVue之Anchor 錨點

用于跳轉到頁面指定位置。 何時使用 需要展現當前頁面上可供跳轉的錨點鏈接&#xff0c;以及快速在錨點之間跳轉。 案例&#xff1a;錨點的基本使用 核心代碼&#xff1a; <template><a-anchor:items"[{key: part-1,href: #part-1,title: () > h(span, {…

大學國學搜題軟件?分享7個軟件和公眾號,來對比看看吧 #經驗分享#微信#媒體

在大學里&#xff0c;高效的學習工具可以幫助我們更好地管理時間和資源&#xff0c;提高學習效果。 1.彩虹搜題 這是個老公眾號了 多語言查詢支持&#xff0c;滿足國際用戶需求。全球通用&#xff0c;無障礙搜題。 下方附上一些測試的試題及答案 1、某酸堿指示劑的&#xf…

Web前端推送功能:深入剖析與應用實踐

Web前端推送功能&#xff1a;深入剖析與應用實踐 在信息化社會的今天&#xff0c;Web前端推送功能作為實時通信和個性化服務的重要手段&#xff0c;受到了廣泛的關注和應用。本文將從四個方面、五個方面、六個方面和七個方面&#xff0c;深入探討Web前端推送功能的原理、應用、…

uniapp自定義的下面導航

uniapp自定義的下面導航 看看效果圖片吧 文章目錄 uniapp自定義的下面導航 看看效果圖片吧 ![在這里插入圖片描述](https://img-blog.csdnimg.cn/direct/6aa0e964741d4dd3a58f4e86c4bf3247.png) 前言一、寫組件、我這里就沒有寫組件了直接寫了一個頁面&#xff1f;總結 前言 在…

職場十大法則:與大家共勉

現在的社會很浮躁&#xff0c;在職的我們也都很浮躁&#xff0c;總是這山望著那山高&#xff0c;都是在為薪資而努力奮斗&#xff08;甚至跳槽&#xff09;。以下是關于職場法則的一些主要內容和建議&#xff0c;與大家共勉&#xff1a; 職場法則一&#xff1a;主動與積極&…

Elasticsearch 認證模擬題 - 12

一、題目 在集群上有 task2 索引&#xff0c;請重建它到 task2_new 索引上&#xff0c;并滿足以下要求&#xff1a; task2 索引的 a 字段包含有關鍵字 Yoo-Hoo 和 YooHoo&#xff0c;不管搜索 Yoo-Hoo 還是YooHoo 它們的結果應該一樣task2_new 和 task2 的 mapping 應該一樣 …

軟件架構x86 、 x86_64、 arm64、aarch64

看系統信息: 大多數Linux發行版都提供如 uname -a命令 arch命令用于顯示當前主機的硬件架構類型。 例如 下面的是Kylin Linux Advanced Server for Kunpeng V10 操作系統 (鯤鵬處理器是華為在2019年1月向業界發布的高性能數據中心處理器 ) 下面這個是 ubuntu 18.04.6 …

CMakeLists如何多行注釋

在使用Visual Studio編寫CMakeLists的時候你可能會遇到需要多行注釋的情況&#xff0c;可又不知道快捷鍵是什么。。。 其實你只需要敲個 #[[ 就行了&#xff0c;另外一般方括號VS會自動幫你補全&#xff0c;之后將需要注釋的內容放在第二個方括號與第三個方括號之間就完成注釋…

1-8 C語言分支循環語句

C語言的語句分為 5 類 1&#xff1a;表達式語句2&#xff1a;函數調用語句3&#xff1a;控制語句4&#xff1a;復合語句5&#xff1a;空語句 控制語句&#xff1a;用于控制程序的執行流程&#xff0c;以實現程序的各種結構方式&#xff0c;它們由特定的語句定義符組成&#x…

Python 機器學習 基礎 之 【實戰案例】中藥數據分析項目實戰

Python 機器學習 基礎 之 【實戰案例】中藥數據分析項目實戰 目錄 Python 機器學習 基礎 之 【實戰案例】中藥數據分析項目實戰 一、簡單介紹 二、中藥數據分析項目實戰 三、數據處理與分析實戰 1、數據讀取 2、中藥材數據集的數據處理與分析 2.1數據清洗 2.2、 提取別…

針對AlGaN/GaN高電子遷移率晶體管的顯式表面電勢計算和緊湊電流模型

來源&#xff1a;An Explicit Surface Potential Calculation and Compact Current Model for AlGaN/GaN HEMTs&#xff08;EDL 15年&#xff09; 摘要 在本文中,我們提出了一種新的緊湊模型,用于基于費米能級和表面電位的顯式解來描述AlGaN/GaN高電子遷移率晶體管。該模型計算…

臺灣合泰原裝BS66F360 封裝LQFP-44 電容觸摸按鍵 AD+LED增強型觸控

BS66F360是一款由Holtek Semiconductor Inc.生產的微控制器&#xff08;microcontroller&#xff09;&#xff0c;具有觸摸檢測和LED驅動功能。其應用領域廣泛&#xff0c;包括但不限于以下幾個方面&#xff1a; 1. 觸摸按鍵應用&#xff1a;BS66F360內置了觸摸按鍵檢測功能&am…

華為云耀云服務器L實例規則配置教程(親自實操經驗)

我剛買了這個最基礎的36&#xffe5;的L實例的云服務器&#xff0c;這個實例是自帶公網ip的&#xff0c;不需要額外購買。我準備先配置好&#xff0c;能夠通過公網ip訪問&#xff0c;以便之后上傳javaweb項目可以直接訪問&#xff0c;不過中途遇到了點問題&#xff0c;但是已解…

富格林:曝光糾正出金虧損陋習

富格林悉知&#xff0c;雖然現貨黃金市場看似變化無常&#xff0c;在操作方向上依舊是有跡可循的&#xff0c;投資者需要了解曝光的專業經驗糾正陋習阻止出金虧損。要獲得優質的黃金投資出金效果&#xff0c;就需要在明確現貨黃金操作技巧的前提下&#xff0c;只有規范遵循已曝…

Ansible——script模塊

目錄 特點 參數總結 使用 ansible 命令 1. 基本示例 2. 傳遞參數 3. 使用 creates 參數 4. 使用 removes 參數 示例 Playbook 文件 基本語法 1. 基本使用 2. 傳遞參數 3. 使用 creates 參數 4. 使用 removes 參數 5. 使用 register 捕獲輸出 6. 使用 args 指定參數…

【Vue】sync修飾符

文章目錄 一、介紹二、語法三、代碼示例 一、介紹 作用&#xff1a;可以實現 子組件 與 父組件數據 的 雙向綁定&#xff0c;簡化代碼 簡單理解&#xff1a;子組件可以修改父組件傳過來的props值 特點&#xff1a;prop屬性名&#xff0c;可以自定義&#xff0c;非固定為valu…

如何安裝 CleanMyMac X 4.15.3破解版

CleanMyMac X 4.15.3破解版是一款專業的Mac系統清理軟件&#xff0c;可一鍵智能掃描清理mac系統日志緩存磁盤垃圾和多余語言安裝包&#xff0c;快速釋放電腦內存&#xff0c;輕松管理和升級Mac上的應用。同時CleanMyMac X 破解版可以強力卸載惡意軟件&#xff0c;修復系統漏洞&…

仿今日頭條的新聞資訊系統

軟件簡介 新聞資訊系統&#xff0c;前端基于 Uniapp、Uview&#xff0c;后端基于Ruoyi系統&#xff0c;代碼易讀易懂、界面簡潔美觀。一套前端代碼&#xff0c;同時支持微信小程序、Android、Ios應用等多種應用。 平臺簡介 新聞資訊系統&#xff0c;主要包括首頁、行業資訊、…

Adobe Illustrator 矢量圖設計軟件下載安裝,Illustrator 輕松創建各種矢量圖形

Adobe Illustrator&#xff0c;它不僅僅是一個簡單的圖形編輯工具&#xff0c;更是一個擁有豐富功能和強大性能的設計利器。 在這款軟件中&#xff0c;用戶可以通過各種精心設計的工具&#xff0c;輕松創建和編輯基于矢量路徑的圖形文件。這些矢量圖形不僅具有高度的可編輯性&a…

高中數學:數列-基礎概念

一、什么是數列&#xff1f; 一般地&#xff0c;我們把按照確定的順序排列的一列數稱為數列&#xff0c;數列中的每一個數叫做這個數列的項&#xff0c;數列的第一項稱為首項。 項數有限個的數列叫做有窮數列&#xff0c;項數無限個的數列叫做無窮數列。 二、一般形式 數列和…