![](/img/trans.png)
[英]combobox's value item(checkbox) checkstate is neutral,how to correct it?
[英]Get item CheckState in a static method
我做了一個擴展方法來交換CheckedListBox中兩個項目的位置。 該方法放在靜態Utilities類中。 問題是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);
我之前沒有使用過CheckedListBox
,但如果我不得不冒險猜測它的MSDN文檔,我會說你想要使用GetItemCheckedState和SetItemCheckedState方法。 但是,這也意味着你必須傳入CheckedListBox
,而不僅僅是它的.Items
ObjectCollection
。
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
; 認為現在考慮到簽名參數的變化會更合適。
也許問題是你應該首先獲得實際列表框項目的當前檢查狀態而不是副本。 您已經知道列表框正在管理與項目列表內容分開的支票!
您還應考慮獲取項目A和B的當前已檢查狀態。執行項目交換后,將已檢查狀態重新應用於這兩個項目,以便為兩個交換項目保持該狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.