c# - 从 WPF DataGridRow 获取项目

标签 c# wpf datagrid

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

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

相关文章:

c# - 从回调中获取 oauth_verifier

c# - 对如何组织我的类(class)有疑问

c# - 无法部署新的 SharePoint 网站模板程序集版本

wpf - 如何在Expander的右上角添加按钮 - WPF DataGrid

c# - 突出显示 WPF 数据网格中的单元格时没有可见文本

c# - 使用 .NET 连接到 iSeries DB2 数据库

wpf - 分组的 CollectionView 的组可以水平呈现吗?

c# - 进度条线程在执行后不会中止,应用程序崩溃-WPF

wpf - WPF:这种类型的CollectionView不支持更改错误

c# - 如何将 WPF DataGrid 绑定(bind)到可变数量的列?