【发布时间】:2017-10-15 20:50:01
【问题描述】:
我必须在列样式为 ComboBox 或 TextBlock 的 DataGrid 中显示一组数据。 DataGrid 绑定到一个DataTable。 DataTable 中每一列的数量和位置是在运行时定义的,因此我以编程方式创建 DataGrid。 只要我使用 DataGridTextColumn 并保留默认样式(TextBlock),一切都很好,而如果我尝试将 DataGridTextColumn 更改为 TextBox 样式,则会出现类型错误。 ComboBox 的问题没有问题,所以我只粘贴了我的代码的 DataGridTextColumn 部分(对于单个 DataGrid 单元格):
C#
// Create the DataTable that will contain real-time data
public DataTable CurrentTable { get; set; }
// Binding string
string stringA = "some_string_A";
// Create new binding
Binding b = new Binding(stringA);
b.Mode = BindingMode.TwoWay;
// Create a new TextColumn
DataGridTextColumn dgCol = new DataGridTextColumn();
//dgCol.ElementStyle = new Style(typeof(TextBox)); <- this row generates error
// Set the column binding for the new TextColumn
dgCol.Binding = b;
// Add the TextColumn to the DataGrid
datagrid.Columns.Add(dgCol);
// Create a new row in the DataTable
var colDataTable = CurrentTable.NewRow();
// Populate column "stringA" of the new row
colDataTable[stringA]="some_string_B";
// Add the row to DataTable
CurrentTable.Rows.Add(colDataTable);
// Finally bind DataGrid to DataTable
datagrid.ItemsSource = CurrentTable.AsDataView();
XAML
<DataGrid x:Name="datagrid" ItemsSource="{Binding CurrentTable}" CanUserAddRows="True" />
我尝试通过多种方式将列样式更改为TetBox,可能我误解了什么,有人可以启发我吗?
【问题讨论】:
标签: wpf datatable datagrid textbox textblock