簡體   English   中英

WPF在使用ItemsSource時將項目從一個列表框移到另一個列表框並再次移回並獲得Operation無效

[英]WPF Moving items from one listbox to another and back again and getting Operation is not valid while ItemsSource is in use

我有兩個列表框。 每個人都從SQLight查詢中獲取數據。 用戶可以通過雙擊項目進行選擇,並且應該將其從LB1中刪除並將其放置在LB2中。 用戶可以選擇從LB2中刪除,並且應該回到LB1,直到他們對選擇滿意為止。 我正在使用LB2中保存的數據來過濾掉LB1中找到的所有項目(按照代碼)。 一旦用戶對所選項目感到滿意,LB2數據將被保存回DB。 用戶可以選擇隨時返回到用戶界面,並根據需要添加/刪除項目。

我正在使用2 x ObservableCollections填充LB1和LB2。 我正在使用模板來控制兩個LB的布局。 IE一旦條目說出列中的10個條目,就會“溢出”到LB中的新列中。

我可以使LB1正確填充,甚至可以將項目移至LB2,但是當我想再次將其移回時,我會...

    "Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead."

我是WPF C#的新手,並且需要有關如何解決此問題的明確說明。 (現在已經努力解決了4個星期)。 該解決方案需要同時應用於兩個ListBoxes。 任何幫助,將不勝感激。

請查看隨附的代碼並發表評論...

CS ...

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

XAML ...

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

修改過的CS文件mouseDoubleClick事件(已針對兩個列表框進行了適當修改)...

            CertificateLookup myListBoxItem = (CertificateLookup)((ListBox)sender).SelectedItem;

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

                            CertificateLookupList.Remove(myListBoxItem);

您的問題是您要向列表框添加項目,而不是向列表框綁定的集合中添加和刪除項目。

而不是這樣做: listBoxCertificateSelected.Items.Add(myListBoxItem); ,您應該直接在CertificateSelectedListCertificateLookupList添加/刪除。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM