user1558012
user1558012

Reputation: 63

CollectionViewSource.GetDefaultView returns null just after SetBinding

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?

Upvotes: 6

Views: 5117

Answers (2)

Gerald Gomes
Gerald Gomes

Reputation: 9

This happens when XmlDataProvider is used. GetDefaultView does not return null when DataContext is set from an object instance from code. However when used XmlDataProvider, GetDefaultView returns null. I found that is because until the xml is loaded it returns null.

Therefore if the CollectionViewSource.GetDefaultView is called from with event handler method of "Loaded" event, it works fine.

public MainWindow()
    {
        InitializeComponent();
        this.comboBox1.Loaded += new RoutedEventHandler(ComboBoxLoaded);           
    }

    private void ComboBoxLoaded(object sender, RoutedEventArgs e)
    {
        ListCollectionView view = (ListCollectionView)CollectionViewSource.GetDefaultView(((XmlDataProvider)this.myGrid.DataContext).Data);
        view.SortDescriptions.Add(new SortDescription("Location", ListSortDirection.Ascending));
    }    

You can find this example following this link (under stage 8):

http://wpfgrid.blogspot.com/2013/01/simple-combobox-implementation.html

Upvotes: 0

LPL
LPL

Reputation: 17063

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());

Upvotes: 3

Related Questions