Get Item from WPF DataGridRow
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. 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
:
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.
Comments
-
user3428422 almost 2 years
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.
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)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