【问题标题】:Get Item from WPF DataGridRow从 WPF DataGridRow 获取项目
【发布时间】:2014-08-21 08:26:25
【问题描述】:

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

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

所以在处理程序中,我尝试获取绑定到行的下划线项目

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 绑定到 DataGrid,而不是 DataGridRow,DataGridRow 无法看到绑定到网格的集合...(我假设)

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

干杯

【问题讨论】:

  • .Item 对象是 {NewItemPlaceholder}
  • 它怎么会是你想要的实际项目..?在我看来,如果您在新行上执行 MouseLeave,那么它将始终返回 PlaceHolder..
  • 这不是一个新行.. 该行已经绑定了一个项目。如果它是生成的新行,我会期待你的说法。

标签: c# wpf datagrid


【解决方案1】:

如果您将事件处理程序附加到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 属性中找到该数据对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-02
    • 2011-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多