0
votes

I have a DataGrid like so:

<DataGrid ItemsSource="{Binding Persons}">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Age}" CellStyle="{StaticResource EditableDataGridCellStyle}" />
    </DataGrid.Columns>
</DataGrid>

I change the style of my DataGridCells with this code

<Style x:Key="EditableDataGridCellStyle" TargetType="DataGridCell">
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="DataGridCell">
                        <TextBox Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content.Text, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Trigger>
    </Style.Triggers>
</Style>

However, when I edit the text of the TextBox, the DataGrid displays the new value, but the underlying Person object does not update his Age. When I get rid of the "EditableDataGridCellStyle" and edit the DataGridCell manually (by double-clicking), it works like I expect.

How can I make sure that an edit of the TextBox will have the same effect as editing a DataGrid cell (i.e., updating the bindings)?

1

1 Answers

0
votes

You should bind to the Age property and nothing else in your template for this to work as expected:

<Style x:Key="EditableDataGridCellStyle" TargetType="DataGridCell">
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="DataGridCell">
                        <TextBox Text="{Binding Age}" />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Trigger>
    </Style.Triggers>
</Style>

And yes, this unfortunately means that you need to define a different Style for each column. You probably better of using a DataGridTemplateColumn: https://msdn.microsoft.com/en-us/library/system.windows.controls.datagridtemplatecolumn(v=vs.110).aspx.