CraigV
CraigV

Reputation: 133

how to default sort wpf listview

I implemented sorting on my listview following this article. How do I get my list to default sort when the window is opened? I tried:

public MainWindow()
        {
            InitializeComponent();
            SortCustomerList("CustomerName", ListSortDirection.Ascending);
        }

...but I'm getting "Exception has been thrown by the target of an invocation"...with an inner exception of "Object reference not set to an instance of an object."

[EDIT] I moved the call to sort to the loaded event as suggested, but I still get the exception? Here's what the sort method and loaded event looks like:

private void SortCustomerList(string sortBy, ListSortDirection direction)
{
   ICollectionView dataView = CollectionViewSource.GetDefaultView(customersListView.ItemsSource);

   dataView.SortDescriptions.Clear();
   SortDescription sd = new SortDescription(sortBy, direction);
   dataView.SortDescriptions.Add(sd);
   dataView.Refresh();
}

private void mainWindow_Loaded(object sender, RoutedEventArgs e)
{
   SortCustomerList("CustomerName", ListSortDirection.Ascending);
}

It's failing on the Clear() method.

Thanks for any suggestions.

Upvotes: 2

Views: 2352

Answers (1)

Paul
Paul

Reputation: 36319

You can't access controls from the constructor in WPF, they're not initialized w/ their data etc. I think the Loaded event is what you want to use, but check the other lifecycle events here: http://msdn.microsoft.com/en-us/library/ms754221.aspx for more info.

Upvotes: 2

Related Questions