Wpf DataGrid: How can I do multiline data entry?

Nov 10, 2008 at 9:25 AM
I am using the WPF Datagrid (from the WpfToolKit).

This grid has the capability to display multline text. If I bind it to a source contains text like

"this is line one" + Environment.NewLine +"this is line two" + Environment.NewLine +"this is line three";

the cell will display three lines of text, and the height of the row will be increased automatically to make the text fully visible.

But: when I click this cell, I cannot enter a NewLine.

How can I edit multiline text? I want to enter more lines, and while entering the text the cell (row) should increase it height automatically.

Norbert Ruessmann
Nov 10, 2008 at 4:48 PM
Something like the following should work for you.....

<toolkit:DataGridTextColumn .....>
        <Style TargetType="{x:Type TextBox}">
            <Setter Property=''AcceptsReturn" Value="True" />

Please note that this would work but the default behavior of 'enter' key (which is to commit the current editing cell and move focus to the cell of next row and same column) will not work with this column.
Jun 17, 2010 at 12:58 PM

I just ran into the same issue with the DataGrid in .NET 4.  It should work like the resource editor in VS: enter commits, shift+enter inserts a newline.  AcceptsReturn is not an acceptable solution because it leaves no way to commit using the keyboard.

It shouldn't have been necessary to do this, but the following code seems to work well:

private void dg_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
    if (Keyboard.IsKeyDown(Key.Enter) && 
        (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)))
        TextBox tb = e.EditingElement as TextBox;
        if (tb != null)
            int selectionStart = tb.SelectionStart;
            string newText = tb.Text.Remove(selectionStart, tb.SelectionLength);
            tb.Text = newText.Insert(selectionStart, Environment.NewLine);
            tb.Select(selectionStart + 1, 0);
            e.Cancel = true;
Honestly I'm a little shocked that the necessary keys are registered in global state as being down at this point, especially enter.  But it works.