【问题标题】:Retrieve databound object for selected row in datagrid检索数据网格中选定行的数据绑定对象
【发布时间】:2013-07-01 16:54:34
【问题描述】:

目前,我正在以这种方式从数据网格(WPF)中检索所选行的实际数据绑定对象:

private void PointListDataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
    PointItem pointItem = (sender as DataGrid).CurrentItem as PointItem;
}

它有效,但这很不雅,需要我施放两次。

Treeview 有一个 SelectedItemChanged 事件,它允许我从事件参数中检索数据绑定对象,但我找不到对 DataGrid 执行相同操作的方法。

如何检索选定行的数据绑定对象?

【问题讨论】:

  • 您好,只是一个简单的问题,但您为什么不使用 MVVM 模式?这样可以更轻松地检索数据网格中选定行的数据绑定对象。
  • 这是最近委托给我的一个项目,几年前开始的,所以我没有选择使它成为 MVVM。虽然我也很好奇使用 MVVM 模式如何使这项任务更容易。您仍然必须捕获事件并以某种方式获取数据绑定对象,不是吗?
  • 使用 MVVM 时不必捕获事件,因为您只需绑定 DataGrid 的 SelectedItem 并直接获取其数据绑定对象。
  • @oldStackExchangeInstance 不过,这只是简单的数据绑定,没有 MVVM 就没有什么不能做的。此外,即使我在 UI 上使用它做一些其他工作,我也需要捕捉所选内容。
  • 如果您想将选定的事件捕获到 ViewModel,我建议您使用 Caliburn.Micro 框架 Message.Attach。 :)

标签: c# .net wpf datagrid


【解决方案1】:

您可以将 PointItem 类型的属性添加到 DataContext 类(例如,包含 DataGrid 的 Window 或 Page 类)并将 CurrentItem 属性绑定到此属性。然后数据绑定为您处理转换,您不必手动进行:

    public PointItem CurrentPointItem
    {
        get { return (PointItem)GetValue(CurrentPointItemProperty); }
        set { SetValue(CurrentPointItemProperty, value); }
    }

    // Using a DependencyProperty as the backing store for CurrentPointItem.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty CurrentPointItemProperty =
        DependencyProperty.Register("CurrentPointItem", typeof(PointItem), typeof(MainWindow), new PropertyMetadata(null));

和您的 xaml(当然,您必须将 DataGrid 或其父级之一的 DataContext 属性设置为包含 CurrentPointItem 属性的对象):

<DataGrid CurrentItem={Binding CurrentPointItem} />

你可以这样写你的活动:

private void PointListDataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
    PointItem pointItem = CurrentPointItem;
    if (pointItem == null)
    {
        //no item selected
    }
}

【讨论】:

    猜你喜欢
    • 2011-11-22
    • 2012-06-29
    • 2012-09-21
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-13
    相关资源
    最近更新 更多