WPF: 'ListView.ItemsSource' property is null during 'Loaded' event

Viewed 1756

So basically, I have a list view set up in XAML like so:

<ListView Margin="0" Name="OpenItemsListView"
    ItemTemplate="{StaticResource DataItemListItemTemplate}"
    ItemsSource="{Binding Path=OpenItems, Mode=OneWay}" 
    Loaded="OpenItemsListView_Loaded"/>

The event handler OpenItemsListView_Loaded looks like this:

private void OpenItemsListView_Loaded(object sender, RoutedEventArgs e) {
    CollectionView view = (CollectionView)CollectionViewSource.GetDefaultView(((ListView)sender).ItemsSource);
    view.GroupDescriptions.Add(new PropertyGroupDescription(nameof(DataItem.ItemTypeGroup)));
}

My problem: I get a null reference exception on the first line of that method because sender.ItemsSource is null, even though I bound it to the window's OpenItems property in the XAML list view declaration. I also checked to make certain that that property is NOT currently set to null at the time the event handler is called.

So, my question is, how can I make sure my event gets called AFTER the list view is all set up and attached to its ItemsSource? Is there a different event I need to handle? Or do I need to do something really hacky and ugly, like start a thread that keeps checking the property in the background to wait for it to not be null, then set up the groups, and then exit? Or maybe there's a completely different simple and pretty solution I should be using?

Thanks in advance.

1 Answers
Related