【问题标题】:WPF Datagrid binding to DataTable and TextBox style in code behindWPF Datagrid 在后面的代码中绑定到 DataTable 和 TextBox 样式
【发布时间】: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


    【解决方案1】:

    您应该将 EditingElementStyle 属性设置为您的TextBox 样式:

    dgCol.EditingElementStyle = new Style(typeof(TextBox));
    

    DataGridTextColumn 有两种样式。一个用于显示,另一个用于编辑。

    【讨论】:

    • 完美!非常感谢!
    猜你喜欢
    • 2011-08-14
    • 2011-04-07
    • 1970-01-01
    • 2013-07-28
    • 2011-08-17
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    • 2018-02-07
    相关资源
    最近更新 更多