Search code examples
wpfdatatabledatagridtextboxtextblock

WPF Datagrid binding to DataTable and TextBox style in code behind


I have to show a set of data in a DataGrid having columns style as ComboBox or TextBlock. The DataGrid is binded to a DataTable. The number and position of each column in the DataTable is defined at runtime, so I create the DataGrid programmatically. Everything is fine as long as I use DataGridTextColumn and leave the default style (TextBlock), while I get a type error if I try to change the DataGridTextColumn to TextBox style. There is no problem for what concerns ComboBox, so I paste hereafter only the DataGridTextColumn part of my code (for a single DataGrid cell):

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" />

I tried to change the column style to TetBox in many ways, probably I misunderstood something, could anybody enlight me?


Solution

  • You should the EditingElementStyle property to your TextBox style:

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

    A DataGridTextColumn has two styles. One for displaying and another one for editing.