Search code examples
c#wpfxamllistviewlistviewitem

How to edit an Item in a ListView?


In my code-behind, how can I edit a value in the ListView ?
I have this :

<ListView x:Name="EntreesListView">
  <ListView.View>
    <GridView>
      <GridViewColumn Header="Entrees" 
                      Width="Auto" 
                      DisplayMemberBinding="{Binding Name}"/>

And this :

// Select all data in my database and add them into my column
private void ListViewAllEntrees()
{
   using (var selectAllEntrees = new Database1Entities())
   {
       var selectName =
           from monEntreeList
           in selectAllEntrees.Entrees
           select monEntreeList;
           foreach (var entree in selectName)
           {
              EntreesListView.Items.Add(new {entree.Name});
           }
// Now I want to edit for example the value at index 5
// I click on a button which is in my ListView too
var item = (sender as FrameworkElement).DataContext;
int indexEntrees = EntreesListView.Items.IndexOf(item);
// Now I have my index
// I can RemoveAt(indexEntrees) and make a new Add but it is not a solution

So how can I do to edit the Value Name at index 5 please ?


Solution

  • There are several methods to accomplish this task.

    Instead of adding each item in list. You can use

    EntreesListView.ItemSource = selectName;
    EntreesListView.Refresh();
    

    now your answer, how to get or modify 5th or any element on some event when you get index of the element which is clicked

    //get the item from original list
    var obj = selectName[index];
    //make changes to your object and again change the ItemSource
    EntreesListView.ItemSource = selectName;
    EntreesListView.Refresh();