C# WPF入门学习主线篇(十)—— DataGrid常见属性和事件

C# WPF入门学习主线篇(十)------ DataGrid常见属性和事件

欢迎来到C# WPF入门学习系列的第十篇。在前面的文章中,我们已经学习了 ButtonTextBoxLabelListBoxComboBox 控件。今天,我们将探讨 WPF 中的另一个重要控件------DataGrid。本文将详细介绍 DataGrid 的常见属性和事件,并通过示例代码展示其在实际应用中的使用。

一、DataGrid的基础知识

DataGrid 是一个非常强大的控件,用于显示和操作表格数据。它允许用户以表格形式查看数据,并支持排序、分组、筛选、编辑等功能。

DataGrid的基本定义

我们先来看看一个简单的 DataGrid 定义:

xml 复制代码
<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 接口的集合。

xml 复制代码
<DataGrid x:Name="myDataGrid" AutoGenerateColumns="True" HorizontalAlignment="Left" VerticalAlignment="Top" Width="500" Height="300"/>
csharp 复制代码
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 时,需要手动定义列。

xml 复制代码
<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 属性设置列标题的高度。

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

4. CanUserAddRows

CanUserAddRows 属性设置用户是否可以添加新行。

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

5. CanUserDeleteRows

CanUserDeleteRows 属性设置用户是否可以删除行。

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

6. IsReadOnly

IsReadOnly 属性设置 DataGrid 是否为只读。

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

示例

下面是一个包含以上常见属性的完整示例:

xml 复制代码
<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>
csharp 复制代码
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代码
xml 复制代码
<DataGrid x:Name="myDataGrid" AutoGenerateColumns="True" LoadingRow="MyDataGrid_LoadingRow" HorizontalAlignment="Left" VerticalAlignment="Top" Width="500" Height="300"/>
后台代码
csharp 复制代码
private void MyDataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
    e.Row.Header = (e.Row.GetIndex() + 1).ToString();
}

2. SelectionChanged

SelectionChanged 事件在选择的项目发生更改时触发。

XAML代码
xml 复制代码
<DataGrid x:Name="myDataGrid" AutoGenerateColumns="True" SelectionChanged="MyDataGrid_SelectionChanged" HorizontalAlignment="Left" VerticalAlignment="Top" Width="500" Height="300"/>
后台代码
csharp 复制代码
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代码
xml 复制代码
<DataGrid x:Name="myDataGrid" AutoGenerateColumns="True" CellEditEnding="MyDataGrid_CellEditEnding" HorizontalAlignment="Left" VerticalAlignment="Top" Width="500" Height="300"/>
后台代码
csharp 复制代码
private void MyDataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    MessageBox.Show("Cell editing is ending.");
}

示例总结

以下是一个包含所有三种常见事件的完整示例:

xml 复制代码
<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>
csharp 复制代码
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

namespace WpfApp
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent(); // 初始化组件

            // 初始化数据源并绑定到 DataGrid
            myDataGrid.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)
        {
            // 获取触发事件的 DataGrid
            DataGrid 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 的基本用法,并在实际项目中灵活运用这些知识。

相关推荐
mudtools12 小时前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
2303_Alpha18 小时前
SpringBoot
笔记·学习
大飞pkz18 小时前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
萘柰奈18 小时前
Unity学习----【进阶】TextMeshPro学习(三)--进阶知识点(TMP基础设置,材质球相关,两个辅助工具类)
学习·unity
沐矢羽19 小时前
Tomcat PUT方法任意写文件漏洞学习
学习·tomcat
好奇龙猫19 小时前
日语学习-日语知识点小记-进阶-JLPT-N1阶段蓝宝书,共120语法(10):91-100语法+考え方13
学习
向阳花开_miemie19 小时前
Android音频学习(十八)——混音流程
学习·音视频
工大一只猿19 小时前
51单片机学习
嵌入式硬件·学习·51单片机
c0d1ng20 小时前
量子计算学习(第十四周周报)
学习·量子计算
唐青枫20 小时前
从入门到进阶:C#.NET Stopwatch 计时与性能测量全攻略
c#·.net