3
votes

I have a datagrid which is bound to an Observable collection in my view model.

The items source property is set to the collection.

Every time I update the collection ( through another button ) , my datagrid view updates and i am able to see the changes .

I want to make sure that atleast one item in the WPF datagrid is selected always .

I tried making Selected Index =0 in the Datagrid XAML , but this works only for initially Loaded datagrid. It doesnt reset the selected index to 0 when the Items source collection is changed . By changed I mean the entire Colelction is reset ( not individual items being added or removed).

Basically I need an event that gets fired from WPF whenever the itemssource collection is reset.

not sure if any code here is helfpul.

2
This could be a duplicate of stackoverflow.com/questions/10708806/…David Zech

2 Answers

1
votes

There are two types of events one can subscribe to and because you are using MVVM where the collection is on the VM, here are the strategies...

Individual Changes

On the View in code behind, subscribe to the ObservableCollection's CollectionChanged event. When the collection changes, the event will be fired and you can specify an index on the grid to be selected depending on the type action that occured.

Collection Change

For whole collection changes, also from the View subscribe to the VM's InotifyProperty change event and do the same logic as mentioned to set a specific item on the grid to be selected.

3
votes

You can subscribe to the PropertyChanged event on your view model and look at the event args to see if the property name matches the name of your DataGrid's ItemsSource. You'll also want to make sure that you are firing that event in your view model (you probably are because your datagrid shows the change).

You could do this in the view's code behind, or better yet, in an attached property.