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;
}
}
}
相关文章
- 09-28整理:WPF中应用附加事件制作可以绑定命令的其他事件
- 09-28WPF中DataGrid垂直滚动条滚动后导致每行CheckBox选择错乱
- 09-28WPF绑定文本时使用指定格式文本
- 09-28WPF多个列表视图绑定到具有不同排序说明的同一集合
- 09-28flex中DataGrid里使用itemRenderer后数据无法绑定到数据源的问题
- 09-28easyui datagrid动态修改editor时动态绑定combobox的数据
- 09-28WPF datagrid 获取行或单格为NULL 问题
- 09-28WPF(五)元素绑定
- 09-28WPF DataGrid 分组
- 09-28【2016-11-15】【坚持学习】【Day26】【WPF 命令绑定到事件】