WinForms 原生 ListBox 不支援項目上下移動。本文提供基於 C# 3.0+ 擴展方法的完整實作,支援多選項目移動、邊界檢查與無選項時的回呼處理,程式碼簡潔優雅,可直接複製使用。
Action 回呼處理「無選項」情況。public static class ListBoxExtension
{
// 批次移動,支援無選項回呼
public static bool MoveSelectedItems(this ListBox listBox, bool isUp, Action noSelectAction)
{
if (listBox.SelectedItems.Count > 0)
return listBox.MoveSelectedItems(isUp);
else
{
noSelectAction();
return false;
}
}
// 批次移動核心邏輯
public static bool MoveSelectedItems(this ListBox listBox, bool isUp)
{
bool result = true;
var indices = listBox.SelectedIndices;
if (isUp)
{
if (listBox.SelectedItems.Count > 0 && indices[0] != 0)
{
foreach (int i in indices)
result &= MoveSelectedItem(listBox, i, true);
}
}
else
{
if (listBox.SelectedItems.Count > 0 && indices[indices.Count - 1] != listBox.Items.Count - 1)
{
for (int i = indices.Count - 1; i >= 0; i--)
result &= MoveSelectedItem(listBox, indices[i], false);
}
}
return result;
}
// 單項移動,支援無選項回呼
public static bool MoveSelectedItem(this ListBox listBox, bool isUp, Action noSelectAction)
{
if (listBox.SelectedItems.Count > 0)
return MoveSelectedItem(listBox, listBox.SelectedIndex, isUp);
else
{
noSelectAction();
return false;
}
}
// 單項移動(預設當前選中)
public static bool MoveSelectedItem(this ListBox listBox, bool isUp)
{
return MoveSelectedItem(listBox, listBox.SelectedIndex, isUp);
}
// 底層單項移動實作
private static bool MoveSelectedItem(this ListBox listBox, int selectedIndex, bool isUp)
{
if (selectedIndex != (isUp ? 0 : listBox.Items.Count - 1))
{
object current = listBox.Items[selectedIndex];
int insertAt = selectedIndex + (isUp ? -1 : 1);
listBox.Items.RemoveAt(selectedIndex);
listBox.Items.Insert(insertAt, current);
listBox.SelectedIndex = insertAt;
return true;
}
return false;
}
}
private void btnUp_Click(object sender, EventArgs e)
{
this.listBox1.MoveSelectedItems(true, () =>
{
MessageBox.Show("請選擇項目");
});
}
private void btnDown_Click(object sender, EventArgs e)
{
this.listBox1.MoveSelectedItems(false, () =>
{
MessageBox.Show("請選擇項目");
});
}
SelectedIndex 更新至新位置,使用者體驗連貫。需 C# 3.0+(.NET Framework 3.5+)支援擴展方法與 Lambda 運算式。若專案為 .NET 2.0,可將擴展方法改為靜態工具類別,Lambda 改為匿名委派即可相容。