C# WPF Combobox select first item

2019-04-18 11:07发布

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条回答
爷、活的狠高调
2楼-- · 2019-04-18 11:34

Update your XAML with this code :

<ComboBox 
   Name="cbGastid" 
   ItemsSource="{Binding}" 
   DisplayMemberPath="Description" 
   SelectedItem="{Binding Path=id, UpdateSourceTrigger=PropertyChanged, Mode=OneWayToSource}"
   IsSynchronizedWithCurrentItem="True" />

Hope it works :)

查看更多
乱世女痞
3楼-- · 2019-04-18 11:37

Try this,

remove from de C# code the following line:

cbGastid.ItemsSource = sitesTable.DefaultView; 

and add this:

cbGastid.DataContext = sitesTable.DefaultView
查看更多
我只想做你的唯一
4楼-- · 2019-04-18 11:49

It works for me if I add a SelectedIndex Property in my VM with the proper binding in the xaml. This is in addition to the ItemSource and the SelectedItem. This way SelectedIndex defaults to 0 and I got what I wanted.

    public List<string> ItemSource { get; } = new List<string> { "Item1", "Item2", "Item3" };
    public int TheSelectedIndex { get; set; }

    string _theSelectedItem = null;
    public string TheSelectedItem
    {
        get { return this._theSelectedItem; }
        set
        {
            this._theSelectedItem = value;
            this.RaisePropertyChangedEvent("TheSelectedItem"); 
        } 
    }

And the proper binding in the xaml;

    <ComboBox MaxHeight="25"  Margin="5,5,5,0" 
      ItemsSource="{Binding ItemSource}" 
      SelectedItem="{Binding TheSelectedItem, Mode=TwoWay}"
      SelectedIndex="{Binding TheSelectedIndex}" />
查看更多
爷的心禁止访问
5楼-- · 2019-04-18 11:51

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.

查看更多
Explosion°爆炸
6楼-- · 2019-04-18 11:58

Update your XAML with this:

<ComboBox 
        Name="cbGastid" 
        ItemsSource="{Binding}" 
        DisplayMemberPath="Description" 
        SelectedItem="{Binding Path=id}"
        IsSynchronizedWithCurrentItem="True"
        SelectedIndex="0" />  // Add me!
查看更多
做个烂人
7楼-- · 2019-04-18 11:58

Try this, instead of SelectedIndex

cbGastid.SelectedItem = sitesTable.DefaultView.[0][0]; // Assuming you have items here.

or set it in Xaml

<ComboBox 
        Name="cbGastid" 
        ItemsSource="{Binding}" 
        DisplayMemberPath="Description" 
        SelectedItem="{Binding Path=id}"
        IsSynchronizedWithCurrentItem="True"
        SelectedIndex="0" />
查看更多
登录 后发表回答