2013-06-23 23 views
1

我做了一個擴展方法,將兩個物品的位置交換到CheckedListBox中。該方法放在一個靜態的Utilities類中。問題是CheckState不能移動。因此,如果我將列表中選中的項目向上移動,複選框狀態將保留,移動的項目將從它正在替換的項目中接管CheckState。以靜態方式獲取物品CheckState

我的代碼如下所示:

public static System.Windows.Forms.CheckedListBox.ObjectCollection Swap(this System.Windows.Forms.CheckedListBox.ObjectCollection lstBoxItems, int indexA, int indexB) 
{ 
    if (indexB > -1 && indexB < lstBoxItems.Count - 1) 
    { 
     object tmpItem = lstBoxItems[indexA];   
     lstBoxItems[indexA] = lstBoxItems[indexB]; 
     lstBoxItems[indexB] = tmpItem; 
    } 
    return lstBoxItems; 
} 

我想是這樣的(不顯着工作)

public static System.Windows.Forms.CheckedListBox.ObjectCollection Swap(this System.Windows.Forms.CheckedListBox.ObjectCollection lstBoxItems, int indexA, int indexB) 
{ 
    if (indexB > -1 && indexB < lstBoxItems.Count - 1) 
    { 
     object tmpItem = lstBoxItems[indexA]; 
     System.Windows.Forms.CheckState state = tmpItem.CheckState; 

     lstBoxItems[indexA] = lstBoxItems[indexB]; 
     lstBoxItems[indexB] = tmpItem; 
    } 
    return lstBoxItems; 
} 

的代碼簡稱像這樣

myCheckedListBox.Items.Swap(selectedIndex, targetIndex); 

回答

3

我以前沒有使用過CheckedListBox,但是如果我不得不冒險查看MSDN文檔爲此,我會說你想要使用GetItemCheckedStateSetItemCheckedState方法。但是,這也意味着您必須通過CheckedListBox而不僅僅是其.ItemsObjectCollection

public static System.Windows.Forms.CheckedListBox Swap(this System.Windows.Forms.CheckedListBox listBox, int indexA, int indexB) 
{ 
    var lstBoxItems = listBox.Items; 
    if (indexB > -1 && indexB < lstBoxItems.Count - 1) 
    { 
     System.Windows.Forms.CheckState stateA = listBox.GetItemCheckState(indexA); 
     System.Windows.Forms.CheckState stateB = listBox.GetItemCheckState(indexB); 

     object tmpItem = lstBoxItems[indexA]; 
     lstBoxItems[indexA] = lstBoxItems[indexB]; 
     lstBoxItems[indexB] = tmpItem; 

     listBox.SetItemCheckState(indexA, stateB); 
     listBox.SetItemCheckState(indexB, stateA); 
    } 
    return listBox; 
} 

所以很自然的調用代碼會改變這樣的事情:

myCheckedListBox.Swap(selectedIndex, targetIndex); 

另外請注意,我的方法返回輸入CheckedListBox以及代替ObjectCollection的;認爲現在考慮到簽名參數的改變會更合適。

+0

謝謝。我只是在看到你的解決方案之前就解決了它 - 我甚至使用了相同的變量名和語法:-)。 Thx驗證它! Upvote並接受那一個。 – Christoffer

1

也許問題是你應該首先獲取實際列表框項目的當前檢查狀態,而不是來自副本。您已經知道列表框正在管理與項目列表內容分開的支票!

你也應該考慮讓目前的狀態檢查兩個項目A和B.執行完,則該項掉期重新選中狀態的兩個項目,使您保持您在交換物品的狀態。

+0

這是很棒的輸入。這實際上爲我解決了另一個問題。我有一個配置文件,獲取列表框中更新的列表。使用您的解決方案,我不必處理在配置文件中進行檢查的每一個列表項目。 – Christoffer