C# DataGrid 用法---极速入门测试

时间:2023-03-10 07:18:37
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="" Width="">
<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 = ; i < ; i++)
{
WsEvlData wd = new WsEvlData();
wd.name = (i + ).ToString();
wd.x = rd.Next(, );
wd.y = rd.Next(, );
wd.z = rd.Next(, ); //Console.WriteLine("{0}",wd.x); data.Add(wd);
} dataGrid.ItemsSource = data; }
}
}

测试中使用了 <随机数>函数,List集合、ArrayList集合 效果相同。

《WPF编程宝典 2012版》中,DataGrid 通过 DataSource 来指定数据源,在这里C# 2015社区版,使用 ItemsSource 来指定数据源。

最终效果:

C# DataGrid 用法---极速入门测试

字符串name、数值x y z 均能正确显示,点击标题栏可以自动排序,滚动条会自动出现,全选后 ctrl+C 可以将数据复制出来。对于一般的数据显示是够用了。