CollectionViewSource.GetDefaultView returns null immediately after SetBinding

I have code in the constructor for WPF UserControl. I basically set the binding to XmlDataProvider (my data is dynamic). Then I want to configure CustomSort to represent as MySorter (implementation of IComparer).

The problem is that GetDefaultView returns null if called immediately after calling SetBinding - as if some asynchronous processing is going on to set up the ItemSource. Please note that if I call the same GetDefaultView code later on the Click handler button, it works fine, it does not return null, and the sorting mechanism 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 immediately after SetBinding, is there some kind of event that I need to wait before I call GetDefaultView and get a non-zero response?

+5
source share
2 answers

Is your Users.ItemsSourcea ItemCollection? Then there will probably be a scan ItemCollectionbecause it inherits from CollectionView.

CollectionViewSource.GetDefaultViewreturns ICollectionView. There are more classes that inherit from CollectionView, and then only ListCollectionView. Make sure your throw is not crashing, for example. with this code:

var view = CollectionViewSource.GetDefaultView(Users.ItemsSource);
Console.WriteLine(view.GetType());
+3
source

, XmlDataProvider. GetDefaultView null, DataContext . XmlDataProvider GetDefaultView null. , , xml null.

, CollectionViewSource.GetDefaultView event- "Loaded", .

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

( 8):

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

0

All Articles