WPF DataGrid-重新部署单元格会导致绑定不更新

WPF DataGrid-重新部署单元格会导致绑定不更新,wpf,xaml,datagrid,Wpf,Xaml,Datagrid,我有这样一个数据网格: <DataGrid ItemsSource="{Binding Persons}"> <DataGrid.Columns> <DataGridTextColumn Binding="{Binding Age}" CellStyle="{StaticResource EditableDataGridCellStyle}" /> </DataGrid.Columns> </DataGrid&

我有这样一个数据网格:

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

我用以下代码更改DataGridCells的样式

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

但是,当我编辑文本框的文本时,DataGrid会显示新值,但底层Person对象不会更新其年龄。当我去掉“EditableDataGridCellStyle”并手动(通过双击)编辑DataGridCell时,它会像我预期的那样工作


如何确保文本框的编辑与编辑DataGrid单元格(即更新绑定)具有相同的效果?

您应该绑定到
Age
属性,而模板中没有任何其他内容可以使其按预期工作:

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


是的,不幸的是,这意味着您需要为每个列定义不同的
样式。您最好使用
DataGridTemplateColumn
:。

这正是我所担心的。我真的希望能够重用这种风格。你知道有什么“黑客”可以从列中指定绑定吗?类似于或者可能我可以重用DataGridTemplateColumn?不。重用样式的唯一方法是以编程方式定义它并以某种方式动态应用它。但这不值得付出努力。在这种情况下,为什么要使用自定义模板?好的,谢谢。我使用自定义模板的目标是使DataGrid的编辑行为对最终用户更加直观。但我走了另一条路,用单击而不是双击来触发单元格编辑。