Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CollectionViewSource.GetDefaultView returns null just after SetBinding

Tags:

c#

.net

wpf

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?

like image 554
user1558012 Avatar asked Jul 27 '12 15:07

user1558012


1 Answers

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());
like image 74
LPL Avatar answered Nov 08 '22 22:11

LPL