WPF如何将ListView中选定的项目传递到另一个ListView?

3

我有一个列表视图,其中包含一些项目。然后我添加了复选框,以便在选择项目时也可以进行勾选。

现在我试图将所选项目从该列表视图传递到另一个列表视图,但是这里是我得到的结果:

enter image description here

这是我的XAML:

<Window x:Class="WpfApp1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp1"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Canvas HorizontalAlignment="Left" Height="299" Margin="10,10,0,0" VerticalAlignment="Top" Width="497">
        <TabControl Height="279" Canvas.Left="10" Canvas.Top="10" Width="477">
            <TabItem Header="TabItem">
                <Grid Background="#FFE5E5E5">
                    <ListView Name="lv1" Margin="0,0,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" Height="110" Width="471">
                        <ListViewItem>
                            <CheckBox >
                                <StackPanel Orientation="Horizontal">
                                    <TextBlock Text="Apple"/>
                                </StackPanel>
                            </CheckBox>
                        </ListViewItem>
                        <ListViewItem>
                            <CheckBox >
                                <StackPanel Orientation="Horizontal">
                                    <TextBlock Text="Orange"/>
                            </StackPanel>
                            </CheckBox>
                        </ListViewItem>
                    </ListView>
                    <Button Content="Copy" Width="100" Height="25" Click="Button_Click"/>
                    <ListView Name="lv2" HorizontalAlignment="Left" VerticalAlignment="Bottom" Height="110" Width="471"/>
                </Grid>
            </TabItem>
            <TabItem Header="TabItem">
                <Grid Background="#FFE5E5E5"/>
            </TabItem>
            <TabItem Header="TabItem">
                <Grid Background="#FFE5E5E5"/>
            </TabItem>
            <TabItem Header="TabItem">
                <Grid Background="#FFE5E5E5"/>
            </TabItem>
            <TabItem Header="TabItem">
                <Grid Background="#FFE5E5E5"/>
            </TabItem>
            <TabItem Header="TabItem">
                <Grid Background="#FFE5E5E5"/>
            </TabItem>
            <TabItem Header="TabItem">
                <Grid Background="#FFE5E5E5"/>
            </TabItem>
        </TabControl>
    </Canvas>

</Grid>

这是C#中的代码后台:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        List<string> lv1list = new List<string>();
        foreach (var i in lv1.SelectedItems)
        {
            lv1list.Add(i.ToString());
        }
        lv2.Items.Add(lv1.SelectedItems);
        }
    }
}

这里出了什么问题?

我在图片中标出了正确的东西吗?我猜你要查看的就是这个问题,对吗? - EJoshuaS - Stand with Ukraine
是的,你做到了。很抱歉我没能做到,感谢您的编辑 :) - user7900863
2个回答

2
问题是您将完整的列表作为一个项目添加,这就是为什么会得到(Collection)值的原因。
您可以做的是获取所有选定的项目并将它们放入一个列表中,然后循环遍历并逐个添加。
private void Button_Click(object sender, RoutedEventArgs e)
{
    var selectedItems = lv1.SelectedItems;

    for(int i = 0; i < selectedItems.Count; i++)
    {
        lv2.Items.Add(selectedItems[i]);
    }
}

在添加新值之前,您可能还需要清除您的lv2

lv2.Items.Clear();

另一个选项是将您的lv2ItemsSource绑定到lv1SelectedItems,这样就不需要按按钮来使值出现在第二个列表视图中。

lv2.ItemsSource = lv1.SelectedItems;

您可以在开始时执行此操作,lv2 将始终包含 lv1 的选定项目,并且会在选定项目更改时立即更新。


感谢您的回答。也许我的XMAL不正确,但现在按钮没有复制任何内容,当我在添加项目到lv2的行处设置断点时,会出现一个未处理的异常类型'System.InvalidOperationException',该异常发生在PresentationFramework.dll中。 额外信息:元素已经有一个逻辑父级。在附加到新父级之前,必须将其从旧父级分离。 - user7900863

2
我进行了一些修改,但后来发现它并没有按照预期工作。我有一个“foreach语句”循环遍历listBox1中所有选中的项目,然后在“foreach语句”内部有一个“If语句”来检查listBox1中选中的项目是否不在listBox2中,如果不在,则将它们复制到listBox2中。每个“If语句”的条件都应显示相关的MessageBox。现在的问题是,“If语句”不能正常工作。我知道这一点,因为我无法看到正确的相关MessageBox与“If语句”的正确条件相对应。然而,项目并没有重复,这意味着它们不会被一遍又一遍地复制,只是在MessageBox中出现重复。以下是我的代码,希望有人能发现我的错误。
using System.Windows;
using System.Windows.Controls;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using System;

namespace MYNAMESPACE
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>

public partial class MainWindow : INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();
        // To initialise the List and use it outside the class
        //MyListItem instanceOfClass = new MyListItem();
        //List<CheckBoxListItem> listOfItems = instanceOfClass.MyMethod();
        //listBox1.ItemsSource = listOfItems;
    }

    public class CheckBoxListItem : INotifyPropertyChanged
    {
        public bool CheckStatus { get; set; }
        public string Text { get; set; }
        public CheckBoxListItem(bool _CheckStatus, string _Text)
        {
            CheckStatus = _CheckStatus;
            Text = _Text;
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

    public class MyListItem
    {
        public List<CheckBoxListItem> MyMethod()
        {
            List<CheckBoxListItem> items = new List<CheckBoxListItem>();
            items.Add(new CheckBoxListItem(false, "Item 1"));
            items.Add(new CheckBoxListItem(false, "Item 2"));
            items.Add(new CheckBoxListItem(false, "Item 3"));

            return items;
        }
    }

    public List<string> selectedNames = new List<string>();
    private void CheckBox_Click(object sender, RoutedEventArgs e)
    {
        var checkBox = sender as CheckBox;
        var item = checkBox.Content;
        bool isChecked = checkBox.IsChecked.HasValue ? checkBox.IsChecked.Value : false;

        if (isChecked)
            selectedNames.Add(item.ToString());
        else
            selectedNames.Remove(item.ToString());
    }

    public string selections;
    bool updatedItems;
    public void Button_Click(object sender, RoutedEventArgs e)
    {
        foreach (string selection in selectedNames)
        {
            selections += selection + Environment.NewLine;

            if (!listBox2.Items.Contains(selection))
            {
                listBox2.Items.Add(selection);
                updatedItems = true;
            }

            else if (listBox2.Items.Contains(selection))
            {
                updatedItems = false;
            }
        }

        if (updatedItems == true)
            MessageBox.Show("Add items are: " + selections);

        else if (updatedItems == false)
            MessageBox.Show("No update to selection was made.");
    }

    private void CheckStatus(string propName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
    }
    public event PropertyChangedEventHandler PropertyChanged;
    }
   }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接