如何在C#中的ListBox的顶部(和底部)移动元素?

时间:2017-01-30 11:48:26

标签: c# winforms listbox

我创建了两个按钮('Move Top'和'Move Bottom'),我必须让它们按如下方式工作。当我点击ListBox中的某个项目时(例如,如果我们有项目: 1。Cat,2。Dog,3。Bird,4。Dinosaur 5..Phoenix 在ListBox中)它直接移动到顶部或底部。

假设我想将元素 Dinosaur 移动到我的ListBox顶部,将元素 Dog 移动到底部。我怎样才能使它工作?再次 - 我应该通过将直接移动到顶部/底部来使其工作。

PS:这是我在这里的第一天,如果我的问题不够明确,请原谅我:)

4 个答案:

答案 0 :(得分:1)

如果您想在位置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

答案 1 :(得分:0)

假设您正在使用MVVM并将ObservableCollection绑定到ListBox

您可以使用IndexOf获取SelectedItem的索引,并使用ObservableCollection的Move方法。

public void Move(int oldIndex, int newIndex)

答案 2 :(得分:0)

你想要类似的东西吗?

       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);
    }

答案 3 :(得分:0)

这应该可以解决问题。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>