My problem is operating with a list and a listview. The Listview’s itemsSource property is bound to a list in my class(say List).
I want to both modify existing items and add new items to the list. For this reason, I’ve made text boxes for each element in the class Contact(name, surname, …)
Now If I want to modify the selected item, I set the Text property of each textbox to this:
<TextBox Text="{Binding ElementName=listView1, Path=SelectedItem.Name}"/>
If I want to create new element. I’ve got to do this:
<TextBox Text="{Binding ElementName=tempContact, Path=Name}"/>
where tempContact is an instance of the Contact class that is lately added to the list via a button.
Problem is I want to do both adding and modifying the elements of this list and I need an idea. Could anyone give me a hand?
To add an item to list from
TextBox, create a property of string type in yourViewModeland notify when the property changes. You have to create a similar property for edit too and also to store current index of selected item from theListViewAdd
TextBoxes andListBoxto your view and apply bindings. This is the tricky part. Because, when you choose an item from theListView, index of the selected item has to be stored in the SelectedIndex property, selected contact name should be bound to theTextBoxused to edit the value.In the Command method that handles the button click, add logic to add or edit an item based on the properties set.
Don’t forget to create your list as an
ObservableCollection. Otherwise, theLisViewwill not be notified about the changes made to list.Hope this helps.