WebEnh

.net7 mvc jquery bootstrap json 学习中 第一次学PHP,正在研究中。自学进行时... ... 我的博客 https://enhweb.github.io/ 不错的皮肤:darkgreentrip,iMetro_HD
随笔 - 1079, 文章 - 1, 评论 - 75, 阅读 - 174万
  首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

WPF开发快速入门【5】DataGrid的使用

Posted on   WebEnh  阅读(731)  评论(0编辑  收藏  举报

概述

DataGrid是最常用的一种列表数据展现控件,本文介绍DataGrid的一些常用操作,包括:展示、新增、删除、修改等。以下代码基于Stylet框架实现。

 

数据展示

DataGrid用于对象列表的展示,我们先定义一个对象DataRecord

复制代码
    public class DataRecord
    {
        public bool IsChecked { get; set; }
        public DateTime Time { get; set; }
        public string Title { get; set; }
        public RecordType RecordType { get; set; }
        public string ImagePath => RecordType == RecordType.File ? "/Images/File.png" : "/Images/Folder.png";
        public double Size { get; set; }
        public bool IsTooLarger => Size > 100;
        public object Tag { get; set; }
        public override string ToString()
        {
            return Title;
        }
    }
复制代码

 后台我们要建两个对象,一个是DataRecord的列表,一个是被选中的DataRecord对象。

复制代码
public class PageDataGridViewModel : Screen
    {
        protected override void OnInitialActivate()
        {
            base.OnInitialActivate();
            InitList();
        }

        public BindableCollection<DataRecord> DataRecordList { get; set; }
        public DataRecord SelectedDataRecord { get; set; } 
    }
复制代码

注意DataRecordList 的类型为BindableCollection<DataRecord> 而不是List<DataRecord>,BindableCollection类是Stylet框架自带的一个列表类型,当用户在操作该控件时,它会发NotifyOfPropertyChange事件给View端。

InitList代码如下:

复制代码
      private void InitList()
        {
            DataRecordList = new BindableCollection<DataRecord>()
            {
                new DataRecord()
                {
                    Title="Hello",
                    Size=10,
                    RecordType= RecordType.Folder
                },
                new DataRecord()
                {
                    Title="World",
                    Size=100.122323232,
                    RecordType= RecordType.Folder
                },
                new DataRecord()
                {
                    Title="Hehe",
                    Size=200,
                    RecordType= RecordType.File,
                    IsChecked=true
                }
            };
        }
View Code
复制代码

设计端代码如下:

               <DataGrid  AutoGenerateColumns="False"
                          ItemsSource="{Binding DataRecordList}"
                          SelectedItem="{Binding SelectedDataRecord}">
                    <DataGrid.Columns>                        
                        <DataGridTextColumn Width="150" Header="Reocrd Time" Binding="{Binding Time,StringFormat='yyyy-MM-dd HH:mm:ss'}" IsReadOnly="True"/>
                        <DataGridTextColumn Width="150" Header="Title" Binding="{Binding Title}"/>             
                    </DataGrid.Columns>
                </DataGrid>

 这样,一个简单的列表就完成了。

 

新增、删除、修改

复制代码
        public void AddNew()
        {
            DataRecordList.Add(new DataRecord()
            {
                Time = DateTime.Now,
                Title="New Item",
            });
        }

        public void Remove()
        {
            DataRecordList.Remove(SelectedDataRecord);
        }       

        public void Update()
        {
            SelectedDataRecord.Title = "Updated";
            SelectedDataRecord.Time = DateTime.Now;
            DataRecordList.Refresh();           
        }
复制代码

 当新增或删除数据时,前端会直接变化,如果是修改数据,需要人为调用BindableCollection类的Refresh()方法。

 

一些常用操作

1、通过数据控制字段显示样式

复制代码
                        <DataGridTextColumn Width="80" Header="Size" Binding="{Binding Size,StringFormat='0.00'}">
                            <DataGridTextColumn.CellStyle>
                                <Style  TargetType="{x:Type DataGridCell}" BasedOn="{StaticResource MahApps.Styles.DataGridCell}">
                                    <Style.Triggers>
                                        <DataTrigger Binding="{Binding IsTooLarger}" Value="True">
                                            <Setter Property="Foreground" Value="Red" />
                                        </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </DataGridTextColumn.CellStyle>
                        </DataGridTextColumn>
复制代码

 

2、通过数据模板显示图片

                        <DataGridTemplateColumn Width="30">
                            <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <Image Source="{Binding ImagePath}" Width="25" Height="25" Margin="2"/>
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>
                        </DataGridTemplateColumn>

 

3、通过数据模板显示CheckBox

                        <DataGridTemplateColumn Header="">
                            <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <CheckBox IsChecked="{Binding IsChecked, UpdateSourceTrigger=PropertyChanged}" />
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>
                        </DataGridTemplateColumn>

当用户修改了CheckBox状态后,后台也能读取到选中的状态。

 

4、显示下拉框

<DataGridComboBoxColumn Header="Type" Width="80" 
              SelectedItemBinding="{Binding RecordType}"
              ItemsSource="{Binding Source={StaticResource RecordTypeEnumKey}}" />

  

资源

系列目录:WPF开发快速入门【0】前言与目录 

代码下载:Learn WPF: WPF学习笔记 (gitee.com)

相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
历史上的今天:
2017-08-19 分享一个Winform里面的HTML编辑控件Zeta HTML Edit Control,汉化附源码
点击右上角即可分享
微信分享提示

喜欢请打赏

扫描二维码打赏

了解更多