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()
I know this question has been answered about 2 years ago, however I had this problem myself as well and thought of a possible solution myself, which works. Maybe this doesn't work in certain scenarios and maybe I'm simply not seeing something, but it worked for me so I'm sharing it here:
listView.ClearValue(ItemsControl.ItemsSourceProperty);
listView.ItemsSource = NewSource;
I sincerely hope this helps someone.
Weird but true: the following errant keystrokes in my XAML file produced the error "Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.":
</ItemsControl.ItemTemplate>x`
Note the "x`" characters after the closing element tag.