简体   繁体   中英

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

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;

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 with valuesList.FirstOrDefault();
  3. On the XAML bind the SelectedItem property of the ListBox to SelectedValue (from ViewModel) and set binding Mode="TwoWay"

这应该工作:

listBox1.SetSelected(0,true);

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM