Editing multiline text in DataGrid (UWP)

A project I am currently working on uses the DataGrid XAML Control from Windows Community Toolkit. By default the data grid only displays single line text-boxes while editing the bound data. The problem for me is that one of the columns in my data set is an address column that requires a multiline textbox editor.

My subsequent search for answers led me to two possible solutions:

Using XAML

One solution is to modify the XAML and edit the EditingElementStyle property for the column:

<controls:DataGridTextColumn Header="Address" Binding="{Binding Address}">
<controls:DataGridTextColumn.EditingElementStyle>
<Style TargetType="TextBox">
<Setter Property="AcceptsReturn" Value="true"/>
</Style>
</controls:DataGridTextColumn.EditingElementStyle>
</controls:DataGridTextColumn>
Copied to clipboard!

But if you are using auto generated columns (AutoGenerateColumns=”True”) as I am, this might not suit your needs.

Using Code Behind

Instead you can use the AutoGeneratingColumn event of the grid control in the code behind file to generate a new DataGridTextColumn object. Then, replace the auto generated column with the newly created one as shown below:

if (e.PropertyName == "Address")
{
DataGridTextColumn tc = new DataGridTextColumn();
tc.Header = e.Column.Header;

tc.Binding = new Binding();
tc.Binding.Mode = BindingMode.TwoWay;
tc.Binding.Path = new PropertyPath("Address");

tc.EditingElementStyle = new Style();
tc.EditingElementStyle.TargetType = typeof(TextBox);

Setter setter = new Setter()
{
Property = TextBox.AcceptsReturnProperty,
Value = true,
};

tc.EditingElementStyle.Setters.Add(setter);

e.Column = tc;
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: