C# DataGrid 用法---极速入门测试
目标:
新手编程,只求DataGrid能运行起来,更多功能留在后面探讨。
步骤:
1、新建WPF文档 插入DataGrid控件。
<Window x:Class="OASevl.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:OASevl" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525"> <Grid> <DataGrid x:Name="dataGrid" /> </Grid> </Window>
2、新建自定义类,用来显示数据。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OASevl { class WsEvlData { public string name { get; set; } public double x { get; set; } public double y { get; set; } public double z { get; set; } } }
类定义中最重要的是增加 get; set; 方法,有了这两个方法,DataGrid 才能显示出来。
3、添加代码进行测试。
namespace OASevl { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); List<WsEvlData> data = new List<WsEvlData>(); //ArrayList data = new ArrayList(); Random rd = new Random(); for (int i = 0; i < 100; i++) { WsEvlData wd = new WsEvlData(); wd.name = (i + 1).ToString(); wd.x = rd.Next(1, 1000); wd.y = rd.Next(1, 1000); wd.z = rd.Next(1, 1000); //Console.WriteLine("{0}",wd.x); data.Add(wd); } dataGrid.ItemsSource = data; } } }
测试中使用了 <随机数>函数,List集合、ArrayList集合 效果相同。
《WPF编程宝典 2012版》中,DataGrid 通过 DataSource 来指定数据源,在这里C# 2015社区版,使用 ItemsSource 来指定数据源。
最终效果:
字符串name、数值x y z 均能正确显示,点击标题栏可以自动排序,滚动条会自动出现,全选后 ctrl+C 可以将数据复制出来。对于一般的数据显示是够用了。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了