简体   繁体   English

从WPF DataGridRow获取项目

[英]Get Item from WPF DataGridRow

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 ItemSource is 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 干杯

If you attach an event handler to the DataGridRow.MouseLeave event, then the sender input parameter will be the DataGridRow as you correctly showed us. 如果将事件处理程序附加到DataGridRow.MouseLeave事件,那么正确显示给我们的sender输入参数将是DataGridRow However, after that you are mistaken. 但是,此后您会弄错。 The DataGridRow.Item property will return the data item from inside the DataGridRow unless you mouse over the last (empty or new) row in the DataGrid ... in that case and that case alone, the DataGridRow.Item property will return a {NewItemPlaceholder} of type MS.Internal.NamedObject : 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.Item property. 尝试将鼠标悬停在实际包含数据的行上,然后应在DataGridRow.Item属性中找到该数据对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM