【问题标题】:WPF DataGrid - retemplating cells causes bindings to not updateWPF DataGrid - 重新模板单元格导致绑定不更新
【发布时间】:2017-11-05 09:02:11
【问题描述】:

我有一个像这样的 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>

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

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

【问题讨论】:

    标签: wpf xaml datagrid


    【解决方案1】:

    您应该绑定到 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>
    

    是的,不幸的是,这意味着您需要为每一列定义不同的Style。你可能最好使用DataGridTemplateColumn:https://msdn.microsoft.com/en-us/library/system.windows.controls.datagridtemplatecolumn(v=vs.110).aspx

    【讨论】:

    • 这就是我害怕的。我真的很希望能够重用这种风格。你知道任何能够从列中指定绑定的“hack”吗?类似 或者我可以重用 DataGridTemplateColumn?
    • 没有。您能够重用样式的唯一方法是以编程方式定义它并以某种方式动态应用它。但这不值得付出努力。在这种情况下,您为什么还要使用自定义模板?
    • 好的,谢谢。我使用自定义模板的目标是使 DataGrid 的编辑行为对我的最终用户来说更加直观。但是我走了另一条路,在单击而不是双击时触发了单元格编辑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-05
    相关资源
    最近更新 更多