TtT23
TtT23

Reputation: 7030

Retrieve databound object for selected row in datagrid

Currently, I'm retrieving the actual databound object of the selected row from a datagrid(WPF) in this fashion:

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

It works, but this is inelegant and it requires me to cast twice.

Treeview had an SelectedItemChanged event which allowed me to retrieve the databound object from the event argument, but I couldn't find a way to do the same thing for DataGrid.

How do I retrieve the databound object for the selected row?

Upvotes: 0

Views: 944

Answers (1)

Dominik Weber
Dominik Weber

Reputation: 427

you could just add a property of type PointItem to your DataContext class (for example the Window or Page class that contains the DataGrid) and bind the CurrentItem property to this property. Then the Data Binding handles the casting for you and you won't have to do it manually:

    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));

and your xaml (of course you would have to set the DataContext property of the DataGrid or one of its parents to the object that contains the CurrentPointItem property):

<DataGrid CurrentItem={Binding CurrentPointItem} />

Than you can write your event like this:

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

Upvotes: 1

Related Questions