WPF DataGrid 绑定 DataTable

DataGrid 绑定 DataTable:

界面:

    <Window x:Class="DataGridBindDataTable.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525">
        <Grid>
            <DataGrid AutoGenerateColumns="False" HorizontalAlignment="Stretch" Margin="5,5" Name="dataGrid1" VerticalAlignment="Stretch" ItemsSource="{Binding}" HorizontalGridLinesBrush="Gainsboro" VerticalGridLinesBrush="Gainsboro">
                <DataGrid.Columns>
                    <DataGridTextColumn Header=" ID " Binding="{Binding ID}" ></DataGridTextColumn>
                    <DataGridTextColumn Header="姓 名" Width ="100" Binding="{Binding Name}" ></DataGridTextColumn>
                    <DataGridTextColumn Header="电 话" Width ="100" Binding="{Binding PhoneNumber}" ></DataGridTextColumn>
                    <DataGridTextColumn Header="住 址" Width ="100" Binding="{Binding Address}" ></DataGridTextColumn>
                </DataGrid.Columns>
            </DataGrid>
        </Grid>
    </Window>


代码:

    using System.Windows;
    using System.Windows.Controls;
    using System.Data;
     
    namespace DataGridBindDataTable
    {
        /// <summary>
        /// MainWindow.xaml 的交互逻辑
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
     
                DataTable dt = new System.Data.DataTable();
                dt.Columns.Add("ID", typeof(int));
                dt.Columns.Add("Name", typeof(string));
                dt.Columns.Add("PhoneNumber", typeof(string));
                dt.Columns.Add("Address", typeof(string));
     
                DataRow row = dt.NewRow();
                row["ID"] = 1;
                row["Name"] = "张三";
                row["PhoneNumber"] = "123456";
                row["Address"] = "北京";
                dt.Rows.Add(row);
     
                row = dt.NewRow();
                row["ID"] = 2;
                row["Name"] = "李四";
                row["PhoneNumber"] = "789001";
                row["Address"] = "上海";
                dt.Rows.Add(row);
     
                //dataGrid1.DataContext = dt;
                dataGrid1.ItemsSource = dt.DefaultView;
     
                //设置网格线
                dataGrid1.GridLinesVisibility = DataGridGridLinesVisibility.All;
     
            }
        }
    }

WPF DataGrid 绑定 DataTable

上一篇:Webapi中messagehandler


下一篇:C# 中的序列化