【问题标题】:Programmatically set ComboBox SelectedItem in WPF (3.5sp1)在 WPF (3.5sp1) 中以编程方式设置 ComboBox SelectedItem
【发布时间】:2011-01-15 02:22:09
【问题描述】:

在安装了 Net Framework 3.5 sp1 的 wpf 应用程序中以编程方式设置 SelectedItem 时,我感到困惑。我仔细阅读了大约一百个帖子\主题,但仍然感到困惑(( 我的xml:

 <ComboBox name="cbTheme">
    <ComboBoxItem>Sunrise theme</ComboBoxItem>
    <ComboBoxItem>Sunset theme</ComboBoxItem> 
 </ComboBox>

如果我在其中一个项目中添加 IsSelected="True" 属性 - 它不会设置该项目被选中。为什么 ? 而且我尝试了不同的代码,但仍然无法设置所选项目:

cbTheme.SelectedItem=cbTheme.Items.GetItemAt(1); //dosn't work
cbTheme.Text = "Sunrise theme"; //dosn't work
cbTheme.Text = cbTheme.Items.GetItemAt(1).ToString();//dosn't work
cbTheme.SelectedValue = ...//dosn't work
cbTheme.SelectedValuePath = .. //dosn't work
//and even this dosn't work:
ComboBoxItem selcbi = (ComboBoxItem)cbTheme.Items.GetItemAt(1);//or selcbi = new ComboBoxItem
cbTheme.SelectedItem = selcbi;

SelectedItem 不是只读属性,为什么它不起作用? 我认为那应该是微软的问题,而不是我的。或者我错过了什么???我尝试过使用 ListBox,并且使用相同的代码都可以正常工作,我可以设置选择,获取选择等等......那么我可以用 ComboBox 做什么?也许有些技巧???

【问题讨论】:

  • 嘿 @Victor 你应该选择 ihatemash 的答案

标签: wpf combobox selecteditem


【解决方案1】:

ComboBox 数据是否绑定?

如果是这样,您可能最好通过绑定而不是代码来实现......

看到这个问题...WPF ListView Programmatically Select Item

也许创建一个新的 SelectableObject {Text = "Abc Theme", IsCurrentlySelected = True} 将一组 SelectableObjects 绑定到 ComboBox。

本质上是在模型中设置 IsCurrentlySelected 属性并从模型中更新 UI。

【讨论】:

    【解决方案2】:

    如果我以编程方式添加组合框和项目,这对我有用:

    ComboBox newCombo = new ComboBox();
    
    ComboBoxItem newitem = new ComboBoxItem();
    newitem.Content = "test 1";
    newCombo.Items.Add(newitem);
    newitem = new ComboBoxItem();
    newitem.Content = "test 2";
    newCombo.Items.Add(newitem);
    newitem = new ComboBoxItem();
    newitem.Content = "test 3";
    newCombo.Items.Add(newitem);
    
    newCombo.SelectedItem =  ((ComboBoxItem)newCombo.Items[1]);
    newCombo.Text = ((ComboBoxItem)newCombo.Items[1]).Content.ToString();
    
    newStack.Children.Add(newCombo);
    

    如果它以编程方式设置ItemSource 属性,然后将文本设置为选定的值,它也可以工作。

    【讨论】:

      【解决方案3】:

      在您的视图模型中为主题列表和所选项目创建一个公共属性:

          private IEnumerable<string> _themeList;
          public IEnumerable<string> ThemeList
          {
              get { return _themeList; }
              set
              {
                  _themeList = value;
                  PropertyChangedEvent.Notify(this, "ThemeList");
              }
          }
          private string _selectedItem;
          public string SelectedItem
          {
              get { return _selectedItem; }
              set
              {
                  _selectedItem = value;
                  PropertyChangedEvent.Notify(this,"SelectedItem");
              }            
          }
      

      将 xaml 中的组合框绑定到如下属性:

          <ComboBox 
              Name="cbTheme" 
              ItemsSource="{Binding ThemeList}"      
              SelectedItem="{Binding SelectedItem}">
          </ComboBox>
      

      现在您只需将项目添加到 ThemeList 以填充组合框。要选择列表中的项目,请将 selected 属性设置为您要选择的项目的文本,如下所示:

          var tmpList = new List<string>();
          tmpList.Add("Sunrise theme");
          tmpList.Add("Sunset theme");
      
          _viewModel.ThemeList = tmpList;
          _viewModel.SelectedItem = "Sunset theme";
      

      如果您想使用您当前拥有的代码,请尝试将所选项目设置为您要在自己的代码中选择的项目的字符串值 - 不确定它是否有效,但您可以尝试。

      【讨论】:

      • 确保将视图的数据文本设置为包含 ThemeList 和 SelectedItem 属性的任何类 - 即您的 ViewModel。
      • 这应该是公认的答案,它是唯一可单元测试的答案
      【解决方案4】:

      根据答案 4

      如果您已经在项目源中添加了项目。 触发选择集值的 PropertyChangedEvent。

      tmpList.Add("Sunrise theme"); 
          tmpList.Add("Sunset theme");
          PropertyChangedEvent.Notify(this,"SelectedItem");
      

      【讨论】:

        【解决方案5】:

        要选择ComboBox 中的任何项目并将其设置为默认项目,只需使用以下行:

        combobox.SelectedIndex = 0; //index should be the index of item which you want to be selected
        

        【讨论】:

          【解决方案6】:

          如果您知道要设置的项目的索引,在这种情况下,您似乎正在尝试设置索引1,您只需这样做:

          cbTheme.SelectedIndex = 1;
          

          我发现,当您不知道索引时,才是真正的问题所在。我知道这超出了最初的问题,但是对于那些想知道如何在索引未知但您想要显示的值已知时设置项目的 Google 员工,如果您使用 @ 填充下拉列表例如,来自DataTable 的 987654323@,您可以通过以下方式获取该索引:

          int matchedIndex = 0;
          if (dt != null & dt.Rows != null)
          {
              if (dt.Rows.Count > 0)
              {
                  foreach (DataRow dr in dt.Rows)
                  {
                      string myRowValue = dr["SOME_COLUMN"] != null ? dr["SOME_COLUMN"].ToString() : String.Empty;
                      if (myRowValue == "Value I Want To Set")
                          break;
                      else
                          matchedIndex++;
                  }
               }
           }
          

          然后您只需执行cbTheme.SelectedIndex = matchedIndex;

          如果 ComboBox 按 OP 显示的方式填充,则 ComboBoxItem 项而不是 DataRow 行的类似迭代可能会产生类似的结果。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2023-03-09
            • 1970-01-01
            • 2011-02-23
            • 2021-12-15
            • 1970-01-01
            • 1970-01-01
            • 2014-05-30
            • 2011-01-10
            相关资源
            最近更新 更多