CollectionViewSource.GetDefaultView 在 SetBinding 之后返回 null

本文关键字:返回 null 之后 SetBinding GetDefaultView CollectionViewSource | 更新日期: 2024-07-27 09:13:56

我在 WPF UserControl 的构造函数中有一些代码。基本上,我设置了一个绑定到 XmlDataProvider (我的数据是动态的(。然后,我想将视图上的自定义排序设置为MySorter(实现IComparer(。

问题是,如果在 SetBinding 调用后直接调用 GetDefaultView,则返回 null - 就好像有一些异步处理正在进行设置 ItemsSource。请注意,如果我稍后在按钮单击处理程序中调用相同的 GetDefaultView 代码,它工作正常,它不会返回 null,并且排序机制都工作正常且花花公子。

MyListBox.SetBinding(ListBox.ItemsSourceProperty, binding);
ListCollectionView view = CollectionViewSource.GetDefaultView(MyListBox.ItemsSource) as ListCollectionView;
view.CustomSort = new MySorter(); // falls over - view is null

我的问题是,为什么在 SetBinding 之后直接调用 GetDefaultView 时返回 null,在调用 GetDefaultView 并获得非空响应之前,我需要等待事件吗?

CollectionViewSource.GetDefaultView 在 SetBinding 之后返回 null

你的Users.ItemsSourceItemCollection吗?那么视图可能也是一个ItemCollection,因为它继承自CollectionView.

CollectionViewSource.GetDefaultView返回一个ICollectionView。有更多的类继承自CollectionView然后只继承ListCollectionView。确保你的强制转换不会失败,例如,使用以下代码:

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

使用 XmlDataProvider 时会发生这种情况。当从代码中的对象实例设置数据上下文时,GetDefaultView 不会返回 null。但是,当使用 XmlDataProvider 时,GetDefaultView 返回 null。我发现这是因为在加载 xml 之前它返回 null。

因此,如果使用"Loaded"事件的事件处理程序方法调用 CollectionViewSource.GetDefaultView,则它可以正常工作。

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