這與我上一篇文章有關。WPF - 實現一個允許項目上下移動的列表框
我想在列表框項目上有上下按鈕 ,以便它們可以向上/向下移動,即在列表中更改其索引 。
任何想法我會如何做到這一點?
Malcolm
這與我上一篇文章有關。WPF - 實現一個允許項目上下移動的列表框
我想在列表框項目上有上下按鈕 ,以便它們可以向上/向下移動,即在列表中更改其索引 。
任何想法我會如何做到這一點?
Malcolm
我很確定你可以將任何你想要的東西扔進ListBox。所以你可以製作自己的控件,它有一個標籤和兩個箭頭按鈕。然後將其放入ListBox並附加事件。
我會做一個按鈕,是向上按鈕,並在其OnClick事件,這樣做:
int location = listItems.SelectedIndex;
if (location > 0)
{
object rememberMe = listItems.SelectedItem;
listItems.Items.RemoveAt(location);
listItems.Items.Insert(location - 1, rememberMe);
listItems.SelectedIndex = location - 1;
}
請記住,這不是測試,因爲我沒有Visual Studio的右側開放現在,但它應該給你一個好主意。
我會在模型中包含項目的順序(即您的數據類)。然後我將列表框綁定到按照該值排序的CollectionView
。然後,您的上/下按鈕就可以簡單地在兩個數據項中交換此排序屬性的值。
你有約束力嗎?嘗試更改綁定對象的項目順序並上載列表框。
使用一個ObservableCollection作爲一個集合爲您的列表框
的ObservableCollection有一個漂亮的Move方法,觸發所有好的事件善良的列表框中迴應...
移
int index = listbox.SelectedIndex;
if (index != -1)
{
if (index > 0)
{
ListBoxItem lbi = (ListBoxItem)listbox.Items[index];
listbox.Items.RemoveAt(index);
index--;
listbox.Items.Insert(index, lbi);
listbox.SelectedIndex = index;
listbox.ScrollIntoView(lbi);
}
}
向下移動
int index = listbox.SelectedIndex;
if (index != -1)
{
if (index < listbox.Items.Count - 1)
{
listboxlbi = (ListBoxItem)listbox.Items[index];
listbox.Items.RemoveAt(index);
index++;
listbox.Items.Insert(index, lbi);
listbox.SelectedIndex = index;
listbox.ScrollIntoView(lbi);
}
}
如果你正在綁定它:
private void MoveItemUp()
{
if (SelectedGroupField != null)
{
List<string> tempList = AvailableGroupField;
string selectedItem = SelectedGroupField;
int currentIndex = tempList.IndexOf(selectedItem);
if (currentIndex > 0)
{
tempList.Remove(selectedItem);
tempList.Insert(currentIndex - 1, selectedItem);
AvailableGroupField = null;
AvailableGroupField = tempList;
SelectedGroupField = AvailableGroupField.Single(p => p == selectedItem);
}
}
}
private void MoveItemDown()
{
if (SelectedGroupField != null)
{
List<string> tempList = AvailableGroupField;
string selectedItem = SelectedGroupField;
int currentIndex = tempList.IndexOf(selectedItem);
if (currentIndex < (tempList.Count - 1))
{
tempList.Remove(selectedItem);
tempList.Insert(currentIndex + 1, selectedItem);
AvailableGroupField = null;
AvailableGroupField = tempList;
SelectedGroupField = AvailableGroupField.Single(p => p == selectedItem);
}
}
}
我還沒有解釋如何將命令綁定到一個方法,假設你已經想通了。