I have two listviews. One of left handside and another on right hand side. I have two buttons to add and remove items from the two listviews.
LHSListview is bound to List and RHSListview is bound to List. Column class has two variables ‘order’ and ‘Id’.
when I click on the add button all the selected items from LHSListview must move to RHSListview. And vice versa when clicked on remove button.
This is what I am trying to do on the click of add button
var list1 = new ArrayList(lstAllFields.SelectedItems);
foreach (var item in list1)
{
lstAllFields.Items.Remove(item);
SelectedFields.Items.Add(item);
}
But this throws an error on lstAllFields.Items.Remove(item); this line saying “Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.”
You mentioned you’re using MVVM, so you probably know that you shouldn’t be changing the items from the ListViews inside the view. What you should do is modify the collection you are bound to in the ViewModel.
Problem is it’s kind of tricky to get the multiple selections in MVVM, because the
SelectedItemsproperty isn’t a Dependency Property.There are 2 ways to achieve what you’re after, both support MVVM:
The shorter and easier way is to listen to the
Button_Clickin the View’s CodeBehind, create a new list of the selected items and pass it to the VM to do the logic of adding and removing items.So a short version would look like this:
Code Behind:
View Model (in my class I called it MainVM)
That’s it. Just remember, the List1 and List2 (which are the
ItemSource‘s thatListView1andListView2bind to, must beObservableCollectionto see the update in the UI.I promised a longer option too, for that see the great 3-part blog post on the subject: