概述

在 WPF 中,将 DataGrid 的数据显示封装成类是 MVVM 模式的最佳实践。通过创建一个数据模型类(Model)和视图模型类(ViewModel),你可以轻松地绑定和管理表格数据。

  • 将 DataGrid 的数据源封装为类,实现:
    • 数据绑定
    • 自动更新 UI
    • 支持增删改查
    • 良好的可维护性

项目结构:
Models/
└── Person.cs // 数据模型
ViewModels/
└── MainViewModel.cs // 视图模型
Views/
└── MainWindow.xaml // 界面

创建工程

创建基于.NET的WPF应用程序DataGridDemo
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

添加类文件

Person.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataGridDemo
{
    public class Person : INotifyPropertyChanged
    {
        private string _name;
        private int _age;
        private string _email;

        public string Name
        {
            get => _name;
            set
            {
                _name = value;
                OnPropertyChanged(nameof(Name));
            }
        }

        public int Age
        {
            get => _age;
            set
            {
                _age = value;
                OnPropertyChanged(nameof(Age));
            }
        }

        public string Email
        {
            get => _email;
            set
            {
                _email = value;
                OnPropertyChanged(nameof(Email));
            }
        }

        // 实现 INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

MainViewModel.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace DataGridDemo
{
    public class MainViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<Person> People { get; set; }
        private Person _selectedPerson;
        public Person SelectedPerson
        {
            get => _selectedPerson;
            set
            {
                _selectedPerson = value;
                OnPropertyChanged(nameof(SelectedPerson));
            }
        }

        public MainViewModel()
        {
            // 初始化数据
            People = new ObservableCollection<Person>
            {
                new Person { Name = "张三", Age = 28, Email = "zhangsan@example.com" },
                new Person { Name = "李四", Age = 32, Email = "lisi@example.com" },
                new Person { Name = "王五", Age = 25, Email = "wangwu@example.com" }
            };
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged([CallerMemberName] string name = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }
    }
}

<Window x:Class="DataGridDemo.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:DataGridDemo"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel Grid.Row="2" Grid.Column="1">
            <DataGrid
                ItemsSource="{Binding People}"
                SelectedItem="{Binding SelectedPerson, Mode=TwoWay}"
                AutoGenerateColumns="False"                
                CanUserAddRows="True"
                CanUserDeleteRows="True"
                GridLinesVisibility="Horizontal"
                VerticalScrollBarVisibility="Visible"
                HeadersVisibility="Column">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="姓名" Binding="{Binding Name, Mode=TwoWay}" Width="*"/>
                    <DataGridTextColumn Header="年龄" Binding="{Binding Age, Mode=TwoWay}" Width="*"/>
                    <DataGridTextColumn Header="邮箱" Binding="{Binding Email, Mode=TwoWay}" Width="*"/>
                </DataGrid.Columns>
            </DataGrid>
        </StackPanel>
    </Grid>
</Window>

MainWindow.xaml.cs
// 设置数据上下文
this.DataContext = new MainViewModel();

using System.Text;
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.Navigation;
using System.Windows.Shapes;

namespace DataGridDemo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            // 设置数据上下文
            this.DataContext = new MainViewModel();
        }
    }
}

运行效果

在这里插入图片描述

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐