I have some code in a constructor for a WPF UserControl. Basically I set a binding to an XmlDataProvider (my data is dynamic). I then want to set the CustomSort on the view to be a MySorter (implementing IComparer).
The problem is that GetDefaultView returns null if called directly after the SetBinding call - as though there is some asynchronous processing going on to set up the ItemsSource. Note that if I call the same GetDefaultView code later in a button Click handler it works fine, it doesn't return null and the sort mechanism all works fine and dandy.
MyListBox.SetBinding(ListBox.ItemsSourceProperty, binding);
ListCollectionView view = CollectionViewSource.GetDefaultView(MyListBox.ItemsSource) as ListCollectionView;
view.CustomSort = new MySorter(); // falls over - view is null
My question is, why does GetDefaultView return null when called directly after SetBinding, is there an event I need to wait for before I call GetDefaultView and get a non-null response?
Is your Users.ItemsSource
an ItemCollection
? Then probably view would be an ItemCollection
too because it inherits from CollectionView
.
CollectionViewSource.GetDefaultView
returns an ICollectionView
. There are more classes which inherit from CollectionView
then ListCollectionView
only. Make sure your cast doesn't fail, e.g. with this code:
var view = CollectionViewSource.GetDefaultView(Users.ItemsSource);
Console.WriteLine(view.GetType());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With