简体   繁体   中英

How do I properly Add and Remove SELECTED items from a listview

So I am currently working on a listview where it's going to populate with items. In this case usernames.
I am deserializing json to create objects, and I am going to take the objects and the NAME property and populate the listview with the names. I've tried making it to where I can remove selected items
but no matter what I do and how I do it, it always ends up throwing an error. Apparently this should be really easy so I need help understanding how to do this in a propper way.

At the current state (see the code below) there are no errors because the code is so slim. It's not even populating the listview at this point. I think it's the databinding that got messed up.

This is what my MainWindow.xaml contains.

<Grid>
        <ListView Name="theListview" HorizontalAlignment="Left" Height="236" Margin="10,10,0,0" VerticalAlignment="Top" Width="497">

            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
                </GridView>
            </ListView.View>
        </ListView>
        <Button Name="btnAdd" Click="btnAdd_Click" Content="Add" HorizontalAlignment="Left" Margin="61,276,0,0" VerticalAlignment="Top" Width="75"/>
        <Button Name="btnRemove" Click="btnRemove_Click" Content="Remove" HorizontalAlignment="Left" Margin="389,276,0,0" VerticalAlignment="Top" Width="75"/>
    </Grid>

And this is my CS

using Newtonsoft.Json;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows;

namespace lvProject
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        string userdata;
        private ObservableCollection<Users> theUsers = new ObservableCollection<Users>();

        public MainWindow()
        {
            InitializeComponent();
        }

        private void PopulateListView()
        {
            using (StreamReader sr = new StreamReader("ops.json"))
            {
                userdata = sr.ReadToEnd();
                List<Users> accounts = JsonConvert.DeserializeObject<List<Users>>(userdata);
                foreach (var account in accounts)
                {
                    theUsers.Add(new Users { Name = account.Name });
                }
            }
        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            //I got the code done for this part, I wont include it because it will make this too long.
        }

        private void btnRemove_Click(object sender, RoutedEventArgs e)
        {
            //I want to remove the SELECTED item from the listview here.
        }
    }
}

JSON

[
  {
    "uuid": "a7c1987f-022c-4310-bd32-21614e7e37b8",
    "name": "Stefan",
    "created": "2017-11-09 21:54:40 +0100",
    "source": "Server",
    "expires": "forever",
    "reason": "Banned by an operator."
  },
  {
    "uuid": "98e99e7a-df48-4b8b-adc9-e65c32410247",
    "name": "Demauen",
    "created": "2017-11-09 20:44:35 +0100",
    "source": "Server",
    "expires": "forever",
    "reason": "Banned by an operator."
  },
  {
    "uuid": "d229d707-27ae-472b-b2df-205713a7c0e0",
    "name": "Kakor",
    "created": "2017-11-09 21:56:02 +0100",
    "source": "Server",
    "expires": "forever",
    "reason": "Banned by an operator."
  },
  {
    "uuid": "af4e2469-0988-4c42-97df-3301a167b658",
    "name": "STEFANOS",
    "created": "2017-11-09 22:26:14 +0100",
    "source": "Server",
    "expires": "forever",
    "reason": "Banned by an operator."
  },
  {
    "uuid": "12e343aa-2c18-45ad-a485-b37838eecd3d",
    "name": "charlies",
    "created": "2017-11-09 22:26:22 +0100",
    "source": "Server",
    "expires": "forever",
    "reason": "Banned by an operator."
  },
  {
    "uuid": "b87e1cbc-c67c-4026-a359-8652ad9de8b4",
    "name": "iVarga",
    "created": "2017-11-09 20:44:38 +0100",
    "source": "Server",
    "expires": "forever",
    "reason": "Banned by an operator."
  },
  {
    "uuid": "eb04608e-cadc-4970-aa57-c60c43fce352",
    "name": "steffe",
    "created": "2017-11-09 22:09:14 +0100",
    "source": "Server",
    "expires": "forever",
    "reason": "Banned by an operator."
  },
  {
    "uuid": "5f95fb35-a2aa-42ac-a99b-e88a013f51b9",
    "name": "Alan",
    "created": "2017-11-09 21:38:20 +0100",
    "source": "Server",
    "expires": "forever",
    "reason": "Banned by an operator."
  }
]

Something like this should work (you need to remove them from the ObservableCollection ):

private void btnRemove_Click(object sender, RoutedEventArgs e)
{
    List<Users> usersToRemove = new List<Users>();

    foreach (Users item in theListview.SelectedItems)
    {
        usersToRemove.Add(item);
    }

    foreach (Users userToRemove in usersToRemove)
    {
        theUsers.Remove(userToRemove);
    }
}

You need to set the ItemsSource of the ListView to the ObservableCollection somewhere.

You could then cast the SelectedItem of the ListView to a Users and remove it from the source collection:

public partial class MainWindow : Window
{
    string userdata;
    private ObservableCollection<Users> theUsers = new ObservableCollection<Users>();

    public MainWindow()
    {
        InitializeComponent();
        theListview.ItemsSource = theListview;
    }

    private void PopulateListView()
    {
        using (StreamReader sr = new StreamReader("ops.json"))
        {
            userdata = sr.ReadToEnd();
            List<Users> accounts = JsonConvert.DeserializeObject<List<Users>>(userdata);
            foreach (var account in accounts)
            {
                theUsers.Add(new Users { Name = account.Name });
            }
        }
    }

    private void btnAdd_Click(object sender, RoutedEventArgs e)
    {
        //I got the code done for this part, I wont include it because it will make this too long.
    }

    private void btnRemove_Click(object sender, RoutedEventArgs e)
    {
        Users selectedUser = theListview.SelectedItem as Users;
        if (selectedUser != null)
            theUsers.Remove(selectedUser);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM