如何在列表视图中正确添加和删除SELECTED项目

时间:2021-02-08 19:36:43

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.

所以我目前正在制作一个列表视图,它将填充项目。在这种情况下用户名。我正在反序列化json以创建对象,我将获取对象和NAME属性并使用名称填充listview。我已经尝试将它移到我可以删除所选项目的地方,但无论我做什么以及如何做,它总是会抛出错误。显然这应该非常简单,所以我需要帮助了解如何以适当的方式做到这一点。

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.

这是我的MainWindow.xaml包含的内容。

<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

这是我的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."
  }
]

2 个解决方案

#1


0  

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

这样的东西应该工作(你需要从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);
    }
}

#2


0  

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

您需要将ListView的ItemsSource设置为ObservableCollection。

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

然后,您可以将ListView的SelectedItem强制转换为用户,并将其从源集合中删除:

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);
    }
}

#1


0  

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

这样的东西应该工作(你需要从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);
    }
}

#2


0  

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

您需要将ListView的ItemsSource设置为ObservableCollection。

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

然后,您可以将ListView的SelectedItem强制转换为用户,并将其从源集合中删除:

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);
    }
}