C# WPF Combobox select first item

女生的网名这么多〃 提交于 2019-12-22 01:33:35

问题


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.


回答1:


Update your XAML with this:

<ComboBox 
        Name="cbGastid" 
        ItemsSource="{Binding}" 
        DisplayMemberPath="Description" 
        SelectedItem="{Binding Path=id}"
        IsSynchronizedWithCurrentItem="True"
        SelectedIndex="0" />  // Add me!



回答2:


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" />



回答3:


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 :)




回答4:


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:


Try this,

remove from de C# code the following line:

cbGastid.ItemsSource = sitesTable.DefaultView; 

and add this:

cbGastid.DataContext = sitesTable.DefaultView



回答6:


Try this..

    int selectedIndex = 0;
    cbGastid.SelectedItem = cbGastid.Items.GetItemAt(selectedIndex);

XAML Code:

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



回答7:


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 is selected in the comboBox or the itemsource is updated, but the element at zero index was not getting selected when the item source is updated. So, what i did, 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 stack overflow link and msdn link for further clarification regarding IsSynchronizedWithCurrentItem="True"

Hope it Helps! :)




回答8:


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.



来源:https://stackoverflow.com/questions/20479976/c-sharp-wpf-combobox-select-first-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!