数据网格文本列的TextChanged/LostFocus等事件

3

我有一个对象列表,绑定到WPF页面的DataGrid上。如果在特定列中输入的值小于某个数,我希望能够直接在当前对象之后添加一个对象。

<my:DataGridTextColumn Binding="{Binding Path=Hours}"/>

我无论如何都无法弄清楚如何绑定到底层的TextBox事件。各个网站都提到了这种能力,但是没有提供相关的代码。目前,我一直在使用一个带有TextBoxDataGridTemplateColumn,但我似乎无法通过这种解决方案获取当前行。


你能具体说明需要获取哪个事件吗?如果我们知道原因,可能会有比事件更优雅的解决方案。 - Aran Mulholland
我正在尝试在特定列的值低于某个数字时,在当前行之后动态添加额外的行。事件可能不是答案,但我对DataGrid的了解还不够,无法找到其他方法。我一直在尝试使用DataGridTemplateColumn中的TextChanged或LostFocus绑定到TextBox进行实验,这种方法可以工作,但是我无法确定行。 - Jake Wharton
2个回答

4
为了实现这个目标,我使用了数据网格本身的CellEditEnding事件。
this.TheGrid.CellEditEnding += new EventHandler<DataGridCellEditEndingEventArgs>(TheGrid_CellEditEnding);

在这种方法中,您可以使用 Dispatcher 来延迟调用方法,以便将值存储回绑定对象。
private void TheGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    Dispatcher.BeginInvoke(new Action(this.CellEdited));
}

你可以将DataGridCellEditEndingEventArgs传递给方法,以允许您检查已编辑的单元格的行和列以及底层TextBox。由于数据网格涉及对象,因此行索引并不太相关,因此难以获得(至少我找不到)。

当行被删除时,它不会被触发。 - Sam

1

您可以使用此代码更新所有单元格和行:

<sdk:DataGrid ItemsSource="{Binding Collection}" CellEditEnded="DataGrid_CellEditEnded" RowEditEnded="DataGrid_RowEditEnded">
    <sdk:DataGrid.Columns>
        <sdk:DataGridTextColumn Binding="{Binding Path=Hours}" Width="Auto" />
    </sdk:DataGrid.Columns>
</sdk:DataGrid>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接