gumenimeda
gumenimeda

Reputation: 835

Selecting first item in listbox

A listbox works as an auto-complete within a richtextbox I am populating it with items from a collection. I need it to auto select first item every time listbox populates.

How do I do this?

Thank you

foreach (var ks in ksd.FindValues(comparable))
      {
          lb.Items.Add(ks.Value);
      }

      if (lb.HasItems)
      {
          lb.Visibility = System.Windows.Visibility.Visible;
          lb.SelectedIndex = 0; //Suggested solution, still doesn't work 
      }
      else
      {
          lb.Visibility = System.Windows.Visibility.Collapsed;
      }

Upvotes: 12

Views: 48188

Answers (4)

Anatolii Gabuza
Anatolii Gabuza

Reputation: 6260

If you're using MVVM then you can also try another solution:

  1. Add property called SelectedValue to the ViewModel;
  2. After loading (or adding) values to the List that you bind to the ListBox set SelectedValue withvaluesList.FirstOrDefault();
  3. On the XAML bind the SelectedItem property of the ListBox to SelectedValue (from ViewModel) and set binding Mode="TwoWay"

Upvotes: 14

This should work:

listBox1.SetSelected(0,true);

Upvotes: 2

theSpyCry
theSpyCry

Reputation: 12283

You don't need anything just the data you use. You shouldn't be interested how the Control looks like. (You don't want to be coupled with that control)

<ListBox ItemsSource="{Binding MyItems}" SelectedItem="{Binding MyItem}" />

could be:

<SexyWoman Legs="{Binding MyItems}" Ass="{Binding MyItem}" />

and it will work as well.

The ListBox has this class as a DataContext:

class DummyClass : INotifyPropertyChanged
{

    private MyItem _myItem;
    public MyItem MyItem
    {
        get { return _myItem; }
        set { _myItem = value; NotifyPropertyChanged("MyItem"); }
    }

    private IEnumerable<MyItem> _myItems;
    public IEnumerable<MyItem> MyItems
    {
        get { return _myItems; }        
    }

    public void FillWithItems()
    {
        /* Some logic */
        _myItems = ...

        NotifyPropertyChanged("MyItems");

        /* This automatically selects the first element */
        MyItem = _myItems.FirstOrDefault();
    }

    #region INotifyPropertyChanged Members
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string value)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(value));
        }
    }
    #endregion
}

Upvotes: -1

Peter PAD
Peter PAD

Reputation: 2310

You can put SelectedIndex to 0 in XAML for the first time loading

<ListBox SelectedIndex="0" />

In code-behind, you can do this after loading items list

        if (this.lst.Items.Count > 0)
            this.lst.SelectedIndex = 0;

Upvotes: 37

Related Questions