2

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I tried moving the sort method call to the loaded event, but I still get an exception.
set a breakpoint on the first line of SorCustomerList and see what's null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.