Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead

You’re binding the ItemsSource to a property in the DataContext called Items, so to update the collection, you need to go to the Items property in the DataContext and clear it.

In addition, the Items property needs to be of type ObservableCollection, not List if you want it to update the UI whenever the underlying collection changes.

Your bit of code that sets the ItemsSource in the code behind is not needed and should be removed. You only need to set the ItemsSource in one place, not both.

Here’s a simple example of how it can work:

// Using Students instead of Items for the PropertyName to clarify
public ObservableCollection<Student> Students { get; set; }

public MyConstructor()
{
    ...

    Students = search.students();
    listBoxSS.DataContext = this;
}

Now when you have:

<ListView ItemsSource="{Binding Students}" ... />

you’re binding the ItemsSource to the ObservableCollection<Student>, and when you want to clear the list you can call:

Students.Clear()

Leave a Comment