C#WPF Combobox选择第一项

时间:2013-12-09 20:22:26

标签: c# wpf xaml combobox dataset

Goodday,

我希望我的组合框选择其中的第一项。我正在使用C#和WPF。我从DataSet中读取数据。填充组合框:

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

组合框XAML代码:

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

如果我尝试:

cbGastid.SelectedIndex = 0; 

它不起作用。

8 个答案:

答案 0 :(得分:31)

使用以下内容更新您的XAML

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

答案 1 :(得分:5)

试试这个,而不是SelectedIndex

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

或在Xaml中设置

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

答案 2 :(得分:2)

使用以下代码更新您的XAML:

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

希望它有效:)

答案 3 :(得分:1)

试试这个,

从de C#代码中删除以下行:

cbGastid.ItemsSource = sitesTable.DefaultView; 

并添加:

cbGastid.DataContext = sitesTable.DefaultView

答案 4 :(得分:1)

如果我在我的VM中添加了一个在xaml中具有正确绑定的SelectedIndex属性,它对我有用。这是ItemSource和SelectedItem的补充。这样SelectedIndex默认为0,我得到了我想要的。

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

在xaml中正确绑定;

    <ComboBox MaxHeight="25"  Margin="5,5,5,0" 
      ItemsSource="{Binding ItemSource}" 
      SelectedItem="{Binding TheSelectedItem, Mode=TwoWay}"
      SelectedIndex="{Binding TheSelectedIndex}" />

答案 5 :(得分:0)

试试这个..

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

XAML代码:

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

答案 6 :(得分:0)

让我分享一下我的解决方案,经过几次试验后对我有用, 这是我的组合框,

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

在我的情况下,每次在comboBox中选择新项目或更新itemsource时都必须调用命令,但是在更新项目源时没有选择零索引处的元素。所以,我做了什么,我补充说。

IsSynchronizedWithCurrentItem="True"

在comboBox属性中,它为我做了诀窍。

我的ViewModel的一些代码如下:

    /// 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();
        }
    }

您可以参考此堆栈溢出link和msdn link以进一步说明IsSynchronizedWithCurrentItem =“True”

希望它有帮助! :)

答案 7 :(得分:0)

这对我有用......给定一个具有一对多关系的作者和书籍表。 XAML看起来像这样:

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

然后我的ViewModel看起来像这样:

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
}

查看ViewModel类的Authors和Books属性。设置完成后,会引发常见的PropertyChanged事件,并将SelectedAuthor / SelectedBook设置为第一个项目。

希望这有帮助。