This question is the result of my previous question DataGrid – grid selection is reset when new Data is arrived
=====================================================================
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));
}
=====================================================================
We have figured out that because I call DataList.Clear the selection in the UI control is cleared as well and I don’t want this to happen. So likely I should not replace instances of ConsoleData in ViewModel, instead of that I should update these instances.
But ObservableCollection observes for add/remove I guess and doesn’t observe for update isn’t? So if I will update instances DataBinding will not work?
Another problem with the current application is that dataList.ForEach(x => DataList.Add(x)); forces databinding to execute on each iteration instead of executing only at the end?
Overall what is the right way to do what I want to do because current application doesn’t work and has too many problems…
It’s not clear how you are planning on updating an item in your
ObservableCollection. There are at least two ways to do this. One way is to update all the properties that are changed in a ConsoleData object. In this case, you would have ConsoleData implementINotifyPropertyChanged. Another way is a direct update of item in theObservableCollection. To do this, you could use theSetItemmethod of theObservableCollection. This will raise theCollectionChangedevent as the MSDN documentation forSetItemindicates.Since you have indicated that you are using MVVM, the generally accepted thing to do would be to make your
ObservableCollectionbe a collection of ConsoleDataViewModel instead of ConsoleData.I don’t think you will have the refresh problem if you modify your model_DataArrived method to update instead of clear/add as indicated above.