从WPF DataGridRow获取项目

本文关键字:项目 获取 DataGridRow WPF | 更新日期: 2023-09-27 18:18:53

我有一个鼠标离开事件当鼠标离开一行

<DataGrid.RowStyle>
     <Style TargetType="DataGridRow">
           <EventSetter Event="MouseLeave" Handler="Row_MouseLeave"></EventSetter>
     </Style>
</DataGrid.RowStyle>

处理程序中,我试着获取与

行有界的下划线项
private void Row_MouseLeave(object sender, MouseEventArgs args)
{
   DataGridRow dgr = sender as DataGridRow;
   <T> = dgr.Item as <T>;
}

但是,项是一个占位符对象,而不是项本身。

通常你可以做我想通过DataGrid selectedIndex属性。

 DataGridRow dgr = (DataGridRow)(dg.ItemContainerGenerator.ContainerFromIndex(dg.SelectedIndex));
 <T> = dgr.Item as <T>

但是由于ItemSource被绑定到DataGrid,而不是DataGridRow, DataGridRow无法看到被绑定到网格的集合…(我认为)

但是因为我没有选择一行,所以我不能这样做。有办法让我做我想做的吗?

欢呼

从WPF DataGridRow获取项目

如果你将事件处理程序附加到DataGridRow.MouseLeave事件,然后sender输入参数将DataGridRow当你正确地给我们看。然而,在那之后,你就错了。DataGridRow.Item属性DataGridRow 内部返回数据项,除非您将鼠标移到DataGrid 中的最后一行(空或新)…在这种情况下,并且仅在这种情况下,DataGridRow.Item属性将返回MS.Internal.NamedObject类型的{NewItemPlaceholder}:

private void Row_MouseLeave(object sender, MouseEventArgs args)
{
    DataGridRow dataGridRow = sender as DataGridRow;
    if (dataGridRow.Item is YourClass)
    {
        YourClass yourItem = dataGridRow.Item as YourClass;
    }
    else if (dataGridRow.Item is MS.Internal.NamedObject)
    {
        // Item is new placeholder
    }
}

尝试将鼠标移到实际包含数据的行上,然后您应该在DataGridRow.Item属性中找到该数据对象。