DataGrid - grid selection is reset when new Data i

2019-03-01 14:32发布

问题:

I have such DataGrid

<DataGrid AutoGenerateColumns="True" HorizontalAlignment="Stretch" Name="dataGrid1" VerticalAlignment="Stretch" ItemsSource="{Binding DataList}" IsReadOnly="True"/>

In my ViewModel I have such field:

public ObservableCollection<ConsoleData> DataList { get; set; }

And such method which is called every second:

private void model_DataArrived(List<ConsoleData> dataList)
{
    DataList.Clear();
    dataList.ForEach(x => DataList.Add(x));
}

Grid displays some real-time data and updates every second.

The problem is - when I select some row in the grid, the selection is reset after a second (when new data is arrived).

I guess probably this is because I Clear DataList every time?

How to solve this problem?

回答1:

Before clear, pick up the currently selected item (a unique identifier if you have one) then attempt to highlight it again on update and if it's not there anymore just don't highlight annything.



回答2:

The way I've set up a updating lists in the past is:

  1. Create an Update method in you object (ConsoleData) that you can pass a copy of that object and the object updates itself. The object also needs to implement INotifyPropertyChanged.

  2. In you model_DataArrived method in the ViewModel find all matching objects and use the Update method from step 1 to update the objects.

  3. Find all new objects and add them to you list (DataList).

  4. Find all missing objects and remove them from you list (DataList).



回答3:

In case the new dataSource still contains your last selected item and if you are following MVVM pattern. All you need to do is Raise PropertyChanged event for your selecetdItem once data source is reloaded. Make sure your viemModel implements INotifyPropertyChanged interface.

EDIT

And in case you don't want to clear your datasource every now and then. Simply, use the ObservableCollection in place of the generic list. It internally implements INotifyCollectionChanged, so any addition or deletion of item in your collection will be reflected on your UI.



标签: c# wpf mvvm