C# WPF Combobox select first item

Viewed 79802

Goodday,

I want my combobox to select the first item in it. I am using C# and WPF. I read the data from a DataSet. To fill the combobox:

DataTable sitesTable = clGast.SelectAll().Tables[0];
cbGastid.ItemsSource = sitesTable.DefaultView;

Combo box XAML code:

<ComboBox 
   Name="cbGastid" 
   ItemsSource="{Binding}" 
   DisplayMemberPath="Description" 
   SelectedItem="{Binding Path=id}"
   IsSynchronizedWithCurrentItem="True" />

If I try:

cbGastid.SelectedIndex = 0; 

It doesn't work.

8 Answers

Let me share my solution, that worked for me after several trials. Here is my combo box:

        <ComboBox   
                Name="fruitComboBox"
                ItemsSource="{Binding Fruits}"
                SelectedIndex="0"
                SelectedValue="{Binding ComboSelectedValue}"
                IsSynchronizedWithCurrentItem="True">

        <i:Interaction.Triggers>
            <i:EventTrigger EventName="SelectionChanged">
                <i:InvokeCommandAction Command="{Binding displayFruitName}"         
                                       CommandParameter="{Binding SelectedValue, ElementName=fruitComboBox}"/>
            </i:EventTrigger>
            <i:EventTrigger EventName="Loaded">
                <i:InvokeCommandAction Command="{Binding displayFruitName}"         
                                       CommandParameter="{Binding SelectedValue, ElementName=fruitComboBox}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers> 
       
        </ComboBox>

In my case, I had to invoke a command every time a new item was selected in the comboBox or when the itemsource was being updated. But, the element at zero index was not getting selected when the item source was updated. So, what did I do? I added:

IsSynchronizedWithCurrentItem="True"

in the comboBox properties. It did the trick for me.

A little code from my ViewModel is below:

    /// item source for comboBox
    private List<string> fruits = new List<string>();
    public List<string> Fruits
    {
        get { return fruits; }
        set 
        {
            fruits = value;
            OnPropertyChanged();
            ComboSelectedValue = value[0];
        }
    }

    // property to which SelectedValue property of comboxBox is bound.
    private string comboselectedValue;
    public string ComboSelectedValue
    {
        get { return comboselectedValue; }
        set 
        { 
            comboselectedValue = value;
            OnPropertyChanged();
        }
    }

You can refer to this stackoverflow link and msdn link for further clarification regarding IsSynchronizedWithCurrentItem="True"

Hope it Helps! :)

This works for me... Given an Authors and Books table with a one-to-many relationship. The XAML Looks like this:

<ComboBox DisplayMemberPath="AuthorName" ItemsSource="{Binding Authors}" Name="ComboBoxAuthors"
              SelectedItem="{Binding SelectedAuthor}"
              IsSynchronizedWithCurrentItem="True" Grid.Row="0" Grid.Column="0"/>
<ComboBox DisplayMemberPath="BookTitle" ItemsSource="{Binding Books}" Name="ComboBoxBooks"
              SelectedItem="{Binding SelectedBook}"
              IsSynchronizedWithCurrentItem="True" Grid.Row="0" Grid.Column="1" />

Then my ViewModel looks like this:

enter public class MainViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    BooksEntities ctx = new BooksEntities();
    List<Author> _authors;
    List<Book> _books;
    Author _selectedAuthor;
    Book _selectedBook;


    public MainViewModel()
    {
        FillAuthors();
    }

    public List<Author> Authors
    {
        get { return _authors; }
        set
        {
            _authors = value;
            NotifyPropertyChanged();
            if (_authors.Count > 0) SelectedAuthor = _authors[0]; // <--- DO THIS
        }
    }

    public Author SelectedAuthor
    {
        get { return _selectedAuthor; }
        set
        {
            _selectedAuthor = value;
            FillBooks();
            NotifyPropertyChanged();
        }
    }

    public List<Book> Books
    {
        get { return _books; }
        set
        {
            _books = value;
            NotifyPropertyChanged();
            if (_books.Count > 0) SelectedBook = _books[0]; // <--- DO THIS
        }
    }

    public Book SelectedBook
    {
        get { return _selectedBook; }
        set
        {
            _selectedBook = value;
            NotifyPropertyChanged();
        }
    }

    #region Private Functions

    private void FillAuthors()
    {
        var q = (from a in ctx.Authors select a).ToList();
        this.Authors = q;
    }

    private void FillBooks()
    {
        Author author = this.SelectedAuthor;

        var q = (from b in ctx.Books
                 orderby b.BookTitle
                 where b.AuthorId == author.Id
                 select b).ToList();
        this.Books = q;
    }

    #endregion
}

Take a look at the Authors and Books properties of the ViewModel class. Once they are set, the usual PropertyChanged event is raised and the SelectedAuthor / SelectedBook is set to the first item.

Hope this helps.

Related