从 WPF DataGridRow 获取项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25421602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:23:14  来源:igfitidea点击:

Get Item from WPF DataGridRow

c#wpfdatagrid

提问by user3428422

I have a mouse leave event for when the mouse leaves a row

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

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

So in the handler, I try to get the underlining item that in bounded to the row

所以在处理程序中,我尝试获取与行有界的下划线项目

private void Row_MouseLeave(object sender, MouseEventArgs args)
{
   DataGridRow dgr = sender as DataGridRow;

   <T> = dgr.Item as <T>;
}

However, the item is a placeholder object and not the item itself.

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

Normally you can do what I want via the DataGrid selectedIndex property.

通常,您可以通过 DataGrid selectedIndex 属性执行我想要的操作。

 DataGridRow dgr = (DataGridRow)(dg.ItemContainerGenerator.ContainerFromIndex(dg.SelectedIndex));

 <T> = dgr.Item as <T>

But as the ItemSourceis bounded to the DataGrid, and not the DataGridRow, the DataGridRow cannot see the collection that was bounded to the grid...(I assume)

但是由于ItemSource绑定到 DataGrid,而不是 DataGridRow,DataGridRow 无法看到绑定到网格的集合......(我假设)

But as I am not selecting a row, I cant really do this. So is there a way I can do what I want?

但由于我没有选择一行,我真的不能这样做。那么有什么方法可以做我想做的事吗?

Cheers

干杯

回答by Sheridan

If you attach an event handler to the DataGridRow.MouseLeaveevent, then the senderinput parameter will be the DataGridRowas you correctly showed us. However, after that you are mistaken. The DataGridRow.Itemproperty willreturn the data item from inside the DataGridRowunless you mouse over the last (empty or new) row in the DataGrid... in that case and that case alone, the DataGridRow.Itemproperty will return a {NewItemPlaceholder}of type MS.Internal.NamedObject:

如果您将事件处理程序附加到DataGridRow.MouseLeave事件,则sender输入参数将是DataGridRow您正确显示的。然而,在那之后你就错了。该DataGridRow.Item物业将会从内返回数据项DataGridRow,除非你把鼠标移到在最后一个(空或新的)行DataGrid......在这种情况下,独自这种情况下,DataGridRow.Item属性将返回一个{NewItemPlaceholder}类型MS.Internal.NamedObject

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

Try mousing over a row that actually contains data and then you should find that data object in the DataGridRow.Itemproperty.

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