这与我上一篇文章有关。
我想在列表框项目上有向上和向下按钮,以便它们可以向上/向下移动,即更改其在列表中的索引。
任何想法我将如何实际做到这一点?
马尔科姆
我会制作一个向上按钮的按钮,并在其 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;
}
请记住,这没有经过测试,因为我现在没有打开视觉工作室,但它应该给你一个好主意。
使用 ObservableCollection 作为 ListBox 的集合
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);
}
}
我会在模型中包含项目的顺序(即您的数据类)。然后我将 ListBox 绑定到CollectionView
按该值排序的 a 。然后,您的向上/向下按钮将简单地在您的两个数据项中交换此排序属性的值。
我很确定你可以将任何你想要的东西扔进 ListBox。因此,您可以制作自己的控件,该控件具有一个标签和两个箭头按钮。然后将其放入 ListBox 并附加事件。
你绑定了吗?尝试更改绑定对象的项目顺序并更新列表框。
如果要绑定它:
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);
}
}
}
我没有解释如何将命令绑定到一个方法,假设你已经知道了。