My DataGrid's ItemsSource is a ListCollectionView, which has a GroupDescription and two SortDescriptions. On the first run of the program, everything works as it should.
However, when the data the ListCollectionView is based on gets changed, the sorting of the ListCollectionView fails (whereas the Grouping does not). It behaves as if the two lines marked as "LINE A" and "LINE B" were not there at all.
public List<MyModel> Models { get; set; }
public ListCollectionView _collectionView;
public MyConstructor()
{
InitializeComponent();
GetData();
Grouping();
}
public void GetData()
{
// fill the list "Models"
}
public void Grouping()
{
// _collectionView = null;
_collectionView = new ListCollectionView(Models);
_collectionView.GroupDescriptions.Add(new PropertyGroupDescription("MyModelSupplier"));
_collectionView.SortDescriptions.Add(new SortDescription("MyModelSupplier", ListSortDirection.Ascending)); // LINE A
_collectionView.SortDescriptions.Add(new SortDescription("MyModelName", ListSortDirection.Ascending)); // LINE B
ModelControl.ItemsSource = _collectionView;
}
private void OnDataChanged (object sender, EventArgs e)
{
// Save the Data to the Database
//...
// Retrieve the Data
GetData();
// Group it again
Grouping();
}
To summarize:
On startup everything looks and behaves like it should. Changing data, saving it to the DataBase and retrieving it again does work also. Just the sorting of the retrieved, grouped data won't work (the list is sorted - like default - by the first property of the MyModel class, which is MyModelName ... and NOT by MyModelSupplier, as it does in the very beginning).
Edit: This is a known bug/missing feature (up until .NET 4.6.2). Several suggestions can be found here (I went with the last solution):
Simple Fix: https://stackoverflow.com/a/10121983/8187945
I am unsure why you are making your
ListCollectionViewin your VM as this is a part ofPresentationFramework.dllso no MvvM in here.However if you use
CollectionViewSourcein your xaml then this would be much easier!in your xaml you would do:
Where:
and then use it for your
DataGridlike so:<DataGrid ItemsSource="{Binding Source={StaticResource events}}"/>This gives you the ability to have these options in xaml and away from your view model.
You can also do this in code behind:
XAML:
and then in your code behind:
If you still have difficulties with the view not being refreshed then you could use this in your code behind to access the items being displayed and just refresh: