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 可以將數據復制出來。對於一般的數據顯示是夠用了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM