Listbox selection

Asked

Viewed 330 times

2

Every time I move an item up or down a listBox he loses focus of the item.

I’m not always able to focus on the item.

For example, let’s assume my list has 200 items. Then I want to move the item that is in position 160 to 159, as soon as moved it loses the selection (focus) of it, in case you want to move from 159 to 158 I will have to click again on the item and select.

public void MoveItem(int direction)
{            
    if (listBox.SelectedItem == null || listBox.SelectedIndex < 0)
        return; 

    int newIndex = listBox.SelectedIndex + direction;

    if (newIndex < 0 || newIndex >= listBox.Items.Count)
        return; 

    object selected = listBox.SelectedItem;

    listBox.Items.Remove(selected);

    listBox.Items.Insert(newIndex, selected);     
}

3 answers

2

I managed to solve the problem

listBox.Focus();
listBox.SelectedIndex = newIndex;

inserted at the end of the code the Focus to then select a new index.

2

After moving the item, place the same as the one selected through your index.

listBox.SelectedIndex = newIndex;

If you do not have access to the desired index, save it in a class variable.

  • I have tried this logic, but it also did not work, he if he wants to selected some item from Listbox, debugging it passes the right value..

  • Did you do this inside the Moveitem() or outside method? Try to put after the method execution.

  • I’ve tried it in and out.

2

You can use the listBox.SetSelected() to select the item back:

public void MoveItem(int direction)
{            
    if (listBox.SelectedItem == null || listBox.SelectedIndex < 0)
        return; 

    int newIndex = listBox.SelectedIndex + direction;

    if (newIndex < 0 || newIndex >= listBox.Items.Count)
        return; 

    object selected = listBox.SelectedItem;

    listBox.Items.Remove(selected);

    listBox.Items.Insert(newIndex, selected);

    listBox.SetSelected(newIndex, true); //Ta aqui o bixo
}

If you have any doubts, take a look at documentation.

  • In wpf there is no such method.

  • Try this: listBox.SelectedItem = listBox.Items.GetItemAt(newIndex);

  • Or this: listBox.SelectedItems.Add(listBox.Items.GetItemAt(newIndex));

  • No , none of the lines worked.

  • Strange. The function listBox.SelectedItems.Add() seems the right one for the situation, you just have to figure out what to pass as parameter.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.