我做了一个扩展方法来交换 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;考虑到签名参数的变化,现在认为这会更合适。
