簡體   English   中英

如何使用通用方法將組合框中的項目移動到列表框中

[英]How can I move items in a combobox to a listbox using a generic method

這是我的第一篇文章,所以請耐心等待。 使用C#,我有一個帶有組合框和列表框的Windows窗體,並且想要將項目從一個對象移動到另一個對象。 我正在嘗試創建一種方法,在該方法中可以傳遞這些對象,並讓算法根據首先傳遞的對象進行工作。 到目前為止,這是我所擁有的,並且該算法可以在代碼的其他地方使用(當我明確聲明Combobox1而不是Obj1或Listbox1而不是Obj2時),但是我想從其in方法中刪除它並創建自己的方法以允許任何包含列表項的對象(例如Listbox,Combobox等)的列表項的移動... Visual Studios說Obj1和Obj2在當前上下文中不存在,我認為是因為它們是在if塊中定義的,但不確定如何解決。 任何幫助表示贊賞。

private void UpdateSelectionListing(object MoveFilesTo, object MoveFilesFrom)
    {
        /* Identify what object will have items moved to, 
         * and what objects will have items moved from */ 
        if (MoveFilesTo is ComboBox && MoveFilesFrom is ListBox)
            {
                ComboBox Obj1 = (ComboBox)MoveFilesTo;
                ListBox Obj2 = (ListBox)MoveFilesFrom;
            }
        else if (MoveFilesTo is ListBox && MoveFilesFrom is ComboBox)
            {
                ComboBox Obj2 = (ComboBox)MoveFilesTo;
                ListBox Obj1 = (ListBox)MoveFilesFrom;
            }

        for (int n = Obj1.Items.Count - 1; n >= 0; --n)
            {
                Obj2.Items.Add(Obj1.Items[n].ToString());
                Obj1.Items.RemoveAt(n);
            }
        } 

您將在if條件中創建實例,這將使其成為明顯的錯誤 。此外,您還可以使其變得更容易,如下所示:

private void UpdateSelectionListing(object MoveFilesTo, object MoveFilesFrom)
 {
     ItemsControl ToObj=MoveFilesTo as ItemsControl;
     ItemsControl FromObj=MoveFilesFrom as ItemsControl;
     List<string> resultList=new List<string>();
      foreach (var item in FromObj.Items)
      {
         resultList.Add(item.ToString());
      }
      FromObj.ItemsSource=null;
      ToObj.ItemsSOurce=resultList;
      FromObj.Items.Refresh();
      ToObj.Items.Refresh();
 } 

暫無
暫無

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

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