XAML DataGrid绑定到运行时空DataTable

时间:2016-08-18 16:11:18

标签: c# wpf xaml datatable datagrid

是否可以将DataGrid绑定到DataTablenew DataTable()在运行时设置为<DataGrid x:Name="dgClients" ItemsSource="{Binding clientsTable}"> <DataGrid.Columns> <DataGridTextColumn Header="Id" Binding="{Binding Path=Id}"/> <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}"/> </DataGrid.Columns> </ViProDataGrid> 但之后填充了列和数据?这是我的XAML:

public DataTable clientsTable = new DataTable(); (global variable)

** the following code is executing after app initialization
DataTable dtTemp = SearchClients(param1);

clientsTable.Columns.Add("Id", dtTemp.Columns["oldIdColumn"].DataType);
clientsTable.Columns.Add("Name", dtTemp.Columns["oldNameColumn"].DataType);

for (int i = 0; i < dtTemp.Rows.Count; i++)
{
   var tmpRow = clientsTable.NewRow();
   tmpRow["Id"] = dtTemp.Rows[i]["oldIdColumn"];
   tmpRow["Name"] = dtTemp.Rows[i]["oldNameColumn"];
   clientsTable.Rows.Add(tmpRow);
}

这是我的c#代码:

DataTable

如果我在填充AutoGenerateColumns="False"并设置DataGrid之后在我的代码中设置了ItemsSource,DataGrid.Items.Refresh()显示的是良好的数据,但这不是我想要的方式。问题是,必须在XAML中设置列。 我尝试使用DataContext并将DataTable设置为 [Test] public void TestExists() { var sql = @"with data as ( select 1 as 'Id' ) select CASE WHEN EXISTS (SELECT Id FROM data WHERE Id = 1) THEN 1 ELSE 0 END AS result from data "; var result = _connection.Query<bool>(sql).FirstOrDefault(); Assert.That(result, Is.True); }

0 个答案:

没有答案