【发布时间】:2009-01-11 06:27:05
【问题描述】:
这与我的上一篇文章有关。
我想在列表框项目上有向上和向下按钮 以便他们可以向上/向下移动,即更改其索引 在列表中。
任何想法我将如何实际做到这一点?
马尔科姆
【问题讨论】:
这与我的上一篇文章有关。
我想在列表框项目上有向上和向下按钮 以便他们可以向上/向下移动,即更改其索引 在列表中。
任何想法我将如何实际做到这一点?
马尔科姆
【问题讨论】:
我会制作一个向上按钮,并在其 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,但它应该给你一个好主意。
【讨论】:
使用 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。然后,您的向上/向下按钮将简单地在您的两个数据项中交换此排序属性的值。
【讨论】:
我很确定你可以将任何你想要的东西放入 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);
}
}
}
我没有解释如何将命令绑定到一个方法,假设你已经知道了。
【讨论】: