Get the marked record

Oct 26, 2008 at 4:57 PM
Hi DevTeam,

the DataGrid works fine, thank you!

My wish: I want to get the marked record, i.e. for Calculations. I think, I should use the CollectionView.CurrentPosition for this job:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
NorthwindDataGrid.ItemsSource = this.dc.Customers.ToList();
NorthwindDataGrid.DataContext = this.dc.Customers;
myGrid.DataContext = this.dc.Customers;
// Does not work:
this.cv = CollectionViewSource.GetDefaultView(this.NorthwindDataGrid.ItemsSource) as CollectionView;
// does not work also:
this.cv = CollectionViewSource.GetDefaultView(this.NorthwindDataGrid.DataContext) as CollectionView;

this.cv.CurrentChanged += new EventHandler(cv_CurrentChanged);
}

My problem: the CollectionView.CurrentChanged does not fire, if I change the row position of the DataGrid. Regardless of binding the CollectionView on DataGrid.ItemsSource or DataGrid.DataContext.

My question: what goes wrong?

-christoph
Coordinator
Oct 30, 2008 at 12:46 PM
Have you tried using DataGrid.CurrentItem?  You also have DataGrid.CurrentCellChanged and you can listen the CurrentItemProperty changed using the DependencyPropertyDescriptor technique.
Oct 31, 2008 at 8:30 PM
Hi vinsibal,

thanks for your tip!

The solution is not the DataGrid to the Table (Customers) to bind but to the CollectionView.
The CollectionView has methods to navigate, and my problem ist solved in one (!) line:

void NorthwindDataGrid_CurrentCellChanged(object sender, EventArgs e)
{
     this.cv.MoveCurrentTo(NorthwindDataGrid.CurrentItem);
}

See also: How to: Navigate Through the Objects in a Data CollectionView.

best Regards,
-christoph