1
我必须在DataGrid中显示具有列样式为ComboBox或TextBlock的一组数据。 DataGrid绑定到一个DataTable。 DataTable中每列的数量和位置是在运行时定义的,所以我通过编程创建了DataGrid。 一切都很好,只要我使用DataGridTextColumn并保留默认样式(TextBlock),而如果我尝试将DataGridTextColumn更改为TextBox样式时出现类型错误。 有什么关注的ComboBox没有问题的,所以我贴以下只是我的代码DataGridTextColumn部分(单DataGrid单元格):WPF Datagrid绑定到DataTable和TextBox样式在代码后面
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,可能我误解了一些东西,有人能让我知道吗?
完美!非常感谢你! – Boltzmann