当鼠标离开一行时,我有一个鼠标离开事件
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<EventSetter Event="MouseLeave" Handler="Row_MouseLeave"></EventSetter>
</Style>
</DataGrid.RowStyle>
因此在处理程序中,我尝试获取与该行绑定(bind)的带下划线的项目
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
绑定(bind)到 DataGrid,而不是 DataGridRow,DataGridRow 看不到绑定(bind)到网格的集合...(我假设)
但是由于我没有选择一行,所以我真的不能这样做。那么有什么方法可以做我想做的事吗?
干杯
最佳答案
如果您将事件处理程序附加到 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
}
}
尝试将鼠标悬停在实际包含数据的行上,然后您应该会在 DataGridRow.Item
属性中找到该数据对象。
关于c# - 从 WPF DataGridRow 获取项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25421602/