【问题标题】:C# WPF Combobox select first itemC# WPF 组合框选择第一项
【发布时间】:2013-12-27 02:44:45
【问题描述】:

晚安,

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

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; 

它不起作用。

【问题讨论】:

  • 你检查你的绑定属性了吗?这推翻了 SelectedIndex!

标签: c# wpf xaml combobox dataset


【解决方案1】:

试试这个,而不是 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" />

【讨论】:

  • ** 错误消息:** 错误 1“System.Data.DataView”不包含“FirstOrDefault”的定义,并且没有扩展方法“FirstOrDefault”接受“System.Data”类型的第一个参数.DataView' 可以找到(您是否缺少 using 指令或程序集引用?) C:\Users\Robin\Dropbox\School KW1C\Leerjaar 3\C#\Campingregistratie\Project\CampingRegistratie\CampingRegistratie\ReserveringenWindow3.xaml.cs 78 37 露营登记处
【解决方案2】:

用这个更新你的XAML

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

【讨论】:

  • 属性IsSynchronizedWithCurrentItem="True"为我工作
  • 谢谢! :) IsSynchronizedWithCurrentItem 为我解决了问题!
  • 为我工作 :) 必须在我的数据源上的索引 0 中插入一个虚拟项目,但一旦我这样做并进行了更改,一切都很好。
  • IsSynchronizedWithCurrentItem="True" 就足够了,不需要 SelectedIndex="0"。
【解决方案3】:

试试这个,

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

cbGastid.ItemsSource = sitesTable.DefaultView; 

并添加:

cbGastid.DataContext = sitesTable.DefaultView

【讨论】:

    【解决方案4】:

    试试这个..

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

    XAML 代码:

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

    【讨论】:

      【解决方案5】:

      如果我在我的 VM 中添加一个 SelectedIndex 属性并在 xaml.这是对 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}" />
      

      【讨论】:

        【解决方案6】:

        使用此代码更新您的 XAML:

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

        希望它有效:)

        【讨论】:

          【解决方案7】:

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

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

          就我而言,每次在组合框中选择新项目或更新项目源时,我都必须调用一个命令。但是,在更新项目源时,未选择零索引处的元素。那么,我做了什么?我补充说:

          IsSynchronizedWithCurrentItem="True"
          

          在组合框属性中。它对我有用。

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

          您可以参考此 stackoverflow link 和 msdn link 以进一步了解 IsSynchronizedWithCurrentItem="True"

          希望对您有所帮助! :)

          【讨论】:

            【解决方案8】:

            这对我有用...给定一个具有一对多关系的 Authors 和 Books 表。 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 被设置为第一项。

            希望这会有所帮助。

            【讨论】:

              猜你喜欢
              • 2022-01-14
              • 2016-08-31
              • 1970-01-01
              • 1970-01-01
              • 2015-08-24
              • 2021-12-23
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多