Part 3 - Applying DataTemplates to create editable TextBoxes for each item instead of read only text
Personally I usually have DataGridViews in ReadOnly mode in winforms and have a separate screen for editing them but I am sure some people use them in the way that lets users edit the data that is in them. So here is an example of how we can apply a DataTemplate to our items to allow the user to edit the data.
First thing we need to do is create the DataTemplate. I usually do this in my window resources tag right at the top of the XAML code, like so:
Code:
<Window.Resources>
<DataTemplate x:Key="FirstNameItemTemplate">
<TextBox Text="{Binding Path=FirstName,UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
</Window.Resources>
What we are doing here is creating a data template and all it does is create a textbox and bind its text property to the FirstName property. Also note that the UpdateSourceTrigger tells our app to update the binding source (our PersonCollection) as soon as a property is changed. This means that as soon as the text is changed the source gets updated, instead of the default setting which only updates the source when focus shifts away from the textbox. Obviously you can remove this if its not necessary in your situation.
So now we can set the First Name column to use this template by changing this line in our original XAML code:
Code:
<GridViewColumn Header="Test Column 1" DisplayMemberBinding="{Binding FirstName}"/>
to this:
Code:
<GridViewColumn Header="First Name" CellTemplate="{StaticResource FirstNameItemTemplate}"/>
We can do the same thing for the Surname column, create a data template for it:
Code:
<DataTemplate x:Key="SurnameItemTemplate">
<TextBox Text="{Binding Path=Surname,UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
and then apply it to the column:
Code:
<GridViewColumn Header="Surname" CellTemplate="{StaticResource SurnameItemTemplate}"/>
Now to make the text boxes stretch to fit our column width instead of being aligned to the left, we can add this style to our Window Resources:
Code:
<Style x:Key="StretchTextBoxStyle" TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment"
Value="Stretch" />
</Style>
and then apply it to the ListView by changing the ListView declaration to loo like this:
Code:
<ListView Margin="14,68,13,26" Name="ListView1" ItemContainerStyle="{StaticResource StretchTextBoxStyle}">
Notice that its the ItemContainerStyle that we are setting to our new style.
And there you go, you should now have an editable grid that updates a collection as it is edited