无法在单元格编辑模板中进行编辑


我有一个带有 DataGridTemplateColumn 的 DataGrid。 我无法编辑评论字段。 当我双击评论字段时,背景会更改为预期的 LightSalmon 以及绑定属性的内容 Comment 显示但我无法编辑内容。

我尝试过的:

<DataGridTemplateColumn IsReadOnly="False" Header="Comment" MinWidth="80">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock
              Background="LightGray"
                Margin="5"
                MinHeight="35"
                TextAlignment="Center"
                Text="{Binding Comment, Mode=OneWay}"
                IsEnabled="True"
                />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <TextBlock
              Background="LightSalmon"
                Opacity="0.5"
                Margin="5"
                MinHeight="35"
                TextAlignment="Center"
                Text="{Binding Comment}"
                IsEnabled="True"
                />
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>

解决方案1

格里给出了解决方案,详细说明了这一点 –

TextBlock 是只读控件,这就是为什么双击它时无法编辑内容的原因 – 微软学习 | 文本块类[^]

要使用编辑功能,您应该在“CellEditingTemplate”中使用可编辑控件,例如“TextBox” –

XAML
<DataGridTemplateColumn IsReadOnly="False" Header="Comment" MinWidth="80">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock
                Background="LightGray"
                Margin="5"
                MinHeight="35"
                TextAlignment="Center"
                Text="{Binding Comment, Mode=OneWay}"
                IsEnabled="True"
            />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <TextBox
                Background="LightSalmon"
                Margin="5"
                MinHeight="35"
                TextAlignment="Center"
                Text="{Binding Comment, UpdateSourceTrigger=PropertyChanged}"
                IsEnabled="True"
            />
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>

“CellEditingTemplate”中的“TextBox”允许您进行用户输入,而“UpdateSourceTrigger=PropertyChanged”可确保源属性随着您的用户输入而更新。

コメント

タイトルとURLをコピーしました