C# 在使用ItemsSource时,WPF将项目从一个列表框移动到另一个列表框,然后再移动回来,获取操作无效

C# 在使用ItemsSource时,WPF将项目从一个列表框移动到另一个列表框,然后再移动回来,获取操作无效,c#,wpf,listbox,observablecollection,C#,Wpf,Listbox,Observablecollection,我有两个列表框。每个都从SQLight查询中获取数据。用户可以通过dbl单击项进行选择,它应该将其从N LB1中删除并放置在LB2中。用户可以选择从LB2中删除,并应移回LB1,直到用户满意选择为止。我正在使用从LB2保存的数据过滤掉在LB1中找到的任何项目(按照代码)。一旦用户对所选项目满意,LB2数据将保存回数据库。用户可以随时返回UI并根据需要添加/删除项目 我使用2 x ObservableCollections来填充LB1和LB2。我使用模板控制两个LB的布局。也就是说,一旦列中的项目

我有两个列表框。每个都从SQLight查询中获取数据。用户可以通过dbl单击项进行选择,它应该将其从N LB1中删除并放置在LB2中。用户可以选择从LB2中删除,并应移回LB1,直到用户满意选择为止。我正在使用从LB2保存的数据过滤掉在LB1中找到的任何项目(按照代码)。一旦用户对所选项目满意,LB2数据将保存回数据库。用户可以随时返回UI并根据需要添加/删除项目

我使用2 x ObservableCollections来填充LB1和LB2。我使用模板控制两个LB的布局。也就是说,一旦列中的项目达到10个,它就会在LB内“溢出”到新的列中

我可以让LB1正确填充,甚至可以将项目移动到LB2,但当我想再次将其移回时,我得到

    "Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead."
我是WPF C#的新手,需要关于如何解决此问题的明确说明。(4周来一直在努力解决此问题)。该解决方案需要应用于两个列表框。在此方面的任何帮助都将不胜感激

请查看所附代码和评论

CS

修改了CS文件mouseDoubleClick事件(对两个列表框进行了适当修改)


您的问题是,您正在向列表框添加项,而不是向列表框绑定到的集合添加和删除项


而不是执行:
listBoxCertificateSelected.Items.Add(myListBoxItem)
,您应该直接从
CertificateSelectedList
CertificateSelectedList
中添加/删除。

非常感谢Blachshma,您让我找到了更新ObservableCollection而不是.Items.Add的正确途径。经修订的守则修订
            using System;
            using System.Windows;
            using System.Windows.Input;
            using System.Windows.Controls;
            using System.Data;
            using System.Data.SQLite;
            using System.Collections;
            using System.Collections.ObjectModel;
            using System.Collections.Generic;
            using PTWS.Class_Lib;

            using System.ComponentModel;
            using System.Windows.Data;
            using System.Windows.Media;


            namespace PTWS.MainPanelControls.FormControls.Permits
            {
                /// <summary>
                /// Interaction logic for ColdWorkDraftUControl.xaml
                /// </summary>
                public partial class ColdWorkDraftUControl : UserControl
                {
                    PTWDatabase db = new PTWDatabase();

                    ObservableCollection<CertificateLookup> CertificateLookupList = new ObservableCollection<CertificateLookup>();
                    ObservableCollection<CertificateSelected> CertificateSelectedList = new ObservableCollection<CertificateSelected>();

                    public ColdWorkDraftUControl()
                    {
                        InitializeComponent();

                        LoadDataCertificateLookup();
                        // all works great untill I uncomment the next line
                        //LoadDataCertificateSelected();            
                    }

                    private void LoadDataCertificateLookup()
                    {
                        try
                        {
                            DataTable conditions;
                            String query = "select lc.Section \"Section\""
                                + ", lc.Description \"Description\""
                                + ", lc.SortOrder \"SortOrder\" "
                                + "from LookupConditions lc "
                                + "where not exists (select 1 from SelectedConditions sc where sc.Code = lc.Code and sc.PermitID = 'CWP-12-00001') "
                                + "and lc.Section = 'Certificates'";

                            conditions = db.GetDataTable(query);

                            foreach (DataRow r in conditions.Rows)
                            {
                                CertificateLookupList.Add(new CertificateLookup()
                                {
                                    Section = r["Section"].ToString(),
                                    Description = r["Description"].ToString(),
                                    SortOrder = r["SortOrder"].ToString()
                                });
                            }

                            listBoxCertificateLookup.ItemsSource = CertificateLookupList;
                        }
                        catch (Exception fail)
                        {
                            String error = "The following error has occurred:\n\n";
                            error += fail.Message.ToString() + "\n\n";
                            MessageBox.Show(error);
                        }
                    }

                    void LoadDataCertificateSelected()
                    {
                        try
                        {
                            DataTable conditions;
                            String query = "select Section \"Section\""
                                + ", Description \"Description\""
                                + ", SortOrder \"SortOrder\"";
                            query += "from SelectedConditions where PermitID = 'CWP-12-00001' and Section = 'Certificates'";
                            conditions = db.GetDataTable(query);



                            foreach (DataRow r in conditions.Rows)
                            {
                                CertificateSelectedList.Add(new CertificateSelected()
                                {
                                    selectedSection = r["Section"].ToString(),
                                    selectedDescription = r["Description"].ToString(),
                                    selectedSortOrder = r["SortOrder"].ToString()
                                });
                            }
                            listBoxCertificateSelected.DataContext = CertificateSelectedList;
                        }
                        catch (Exception fail)
                        {
                            String error = "The following error has occurred:\n\n";
                            error += fail.Message.ToString() + "\n\n";
                            MessageBox.Show(error);
                        }
                    }

                    private void listBoxCertificateLookup_MouseDoubleClick(object sender, MouseButtonEventArgs e)
                    {
                        try
                        {
                            ListBoxItem myListBoxItem =
                                (ListBoxItem)(listBoxCertificateLookup.ItemContainerGenerator.ContainerFromItem(listBoxCertificateLookup.Items.CurrentItem));
                            // listBoxCertificateSelected.DataContext = null;
                            listBoxCertificateSelected.Items.Add(myListBoxItem);
                        }
                        catch (Exception fail)
                        {
                            String error = "The following error has occurred:\n\n";
                            error += fail.Message.ToString() + "\n\n";
                            MessageBox.Show(error);
                        }
                    }

                    private void listBoxCertificateSelected_MouseDoubleClick(object sender, MouseButtonEventArgs e)
                    {
                        try
                        {
                            ListBoxItem myListBoxItem =
                                (ListBoxItem)(listBoxCertificateSelected.ItemContainerGenerator.ContainerFromItem(listBoxCertificateSelected.Items.CurrentItem));

                            //listBoxCertificateLookup.DataContext = null;
                            listBoxCertificateLookup.Items.Add(myListBoxItem);
                        }
                        catch (Exception fail)
                        {
                            String error = "The following error has occurred:\n\n";
                            error += fail.Message.ToString() + "\n\n";
                            MessageBox.Show(error);
                        }
                    }
                }
            }
            <UserControl x:Class="PTWS.MainPanelControls.FormControls.Permits.ColdWorkDraftUControl"
                         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
                         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
                         mc:Ignorable="d" 
                         d:DesignHeight="300" d:DesignWidth="300">

                <Grid>
                    <ListBox Name="listBoxCertificateLookup"
                             ItemsSource="{Binding CertificateSelectedList}"
                             MouseDoubleClick="listBoxCertificateLookup_MouseDoubleClick"
                             IsSynchronizedWithCurrentItem="True"
                             HorizontalAlignment="Left" Width="300" Height="75" VerticalAlignment="Top" >
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <StackPanel Height="23" Orientation="Horizontal">
                                    <TextBlock Text="{Binding Path=Description}" VerticalAlignment="Top" />
                                </StackPanel>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
                        <ListBox.ItemsPanel>
                            <ItemsPanelTemplate>
                                <WrapPanel IsItemsHost="True" Orientation="Vertical" />
                            </ItemsPanelTemplate>
                        </ListBox.ItemsPanel>
                    </ListBox>

                    <ListBox Name="listBoxCertificateSelected"
                             ItemsSource="{Binding}"
                             MouseDoubleClick="listBoxCertificateSelected_MouseDoubleClick"
                             HorizontalAlignment="Left" Width="300" Height="75" VerticalAlignment="Top" Margin="0,153,0,0">
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <StackPanel Height="23" Orientation="Horizontal">
                                    <TextBlock Name="textBlock" Text="{Binding Path=selectedDescription}" VerticalAlignment="Top" />
                                </StackPanel>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
                        <ListBox.ItemsPanel>
                            <ItemsPanelTemplate>
                                <WrapPanel IsItemsHost="True" Orientation="Vertical" />
                            </ItemsPanelTemplate>
                        </ListBox.ItemsPanel>
                    </ListBox>
                </Grid>
            </UserControl> 
            using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Text;

            namespace PTWS.Class_Lib
            {
                class CertificateLookup
                {
                    public string Section { get; set; }
                    public string Description {get; set;}
                    public string SortOrder { get; set; }

                    public string selectedSection { get; set; }
                    public string selectedDescription { get; set; }
                    public string selectedSortOrder { get; set; }
                }
            }
            CertificateLookup myListBoxItem = (CertificateLookup)((ListBox)sender).SelectedItem;

                            CertificateSelectedList.Add(new CertificateSelected()
                            {
                                selectedDescription = myListBoxItem.Description
                            });

                            CertificateLookupList.Remove(myListBoxItem);