检索datagrid中所选行的数据绑定对象

时间:2013-07-01 16:54:35

标签: c# .net wpf datagrid

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

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

它有效,但这不够优雅,需要我施展两次。

Treeview有一个SelectedItemChanged事件,它允许我从事件参数中检索数据绑定对象,但我找不到为DataGrid做同样事情的方法。

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

1 个答案:

答案 0 :(得分: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
    }
}