如何移动C#中ListBox顶部(和底部)的元素?
问题描述:
我已经创建了两个按钮('Move Top'和'Move Bottom'),我必须让它们按如下方式工作。当我从列表框中单击一个项目(例如,如果我们有项目:1.猫,2.狗,3.鸟,4.恐龙和5.菲尼克斯在列表框中)它直接移动到顶部或底部。如何移动C#中ListBox顶部(和底部)的元素?
比方说,我想元素恐龙移动到我的列表框的顶部,和元素狗 - 底部。我怎样才能使它工作?再次 - 我应该通过将其移动到直接到顶部/底部。
PS:这是我第一天在这里,所以原谅我,如果我的问题不够清楚:)
答
如果你想在位置0(开始)在ListBox
插入一个项目,你可以使用:
ListBox c = new ListBox();
string item="Some string";
c.Items.Insert(0, item); //added as first item in Listbox
,如果你想在列表框中使用的末尾插入:
c.Items.Add(item); //add at the end
答
假设你正在使用MVVM和有约束力的ObservableCollection
您ListBox
。
您可以使用IndexOf
获得SelectedItem的索引,并使用ObservableCollection
的Move方法。
public void Move(int oldIndex, int newIndex)
答
你想要类似的东西吗?
public void MoveUp()
{
MoveItem(-1);
}
public void MoveDown()
{
MoveItem(1);
}
public void MoveItem(int direction)
{
// Checking selected item
if (yourListBox.SelectedItem == null || yourListBox.SelectedIndex < 0)
return; // No selected item - nothing to do
// Calculate new index using move direction
int newIndex = yourListBox.SelectedIndex + direction;
// Checking bounds of the range
if (newIndex < 0 || newIndex >= yourListBox.Items.Count)
return; // Index out of range - nothing to do
object selected = yourListBox.SelectedItem;
// Removing removable element
yourListBox.Items.Remove(selected);
// Insert it in new position
yourListBox.Items.Insert(newIndex, selected);
// Restore selection
yourListBox.SetSelected(newIndex, true);
}
答
这应该可以做到。
public void MoveToTop(ListBox lb, int index) {
var item = lb.Items[index];
lb.Items.RemoveAt(index);
lb.Items.Insert(0, item);
lb.Refresh();
}
public void MoveToBottom(ListBox lb, int index) {
var item = lb.Items[index];
lb.Items.RemoveAt(index);
lb.Items.Add(item);
lb.Refresh();
}
你在用什么? WPF,WinForms,ASP.NET,ASP.MVC – trebor
我正在使用Windows窗体 –
[C#将项目移到顶部](http://stackoverflow.com/questions/28309764/c-sharp-move -Item-在-列表框到最顶部) – Sinatr