WPF Datagrid 在代码隐藏中绑定到 DataTable 和 TextBox 样式
WPF Datagrid binding to DataTable and TextBox style in code behind
我必须在列样式为 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,可能是我误解了什么,有人可以指导我吗?
您应该 EditingElementStyle 属性 到您的 TextBox
风格:
dgCol.EditingElementStyle = new Style(typeof(TextBox));
一个DataGridTextColumn
有两种样式。一个用于显示,另一个用于编辑。
我必须在列样式为 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,可能是我误解了什么,有人可以指导我吗?
您应该 EditingElementStyle 属性 到您的 TextBox
风格:
dgCol.EditingElementStyle = new Style(typeof(TextBox));
一个DataGridTextColumn
有两种样式。一个用于显示,另一个用于编辑。