【问题标题】:How to set selectedValue to Controls.Combobox in c#?如何在 c# 中将 selectedValue 设置为 Controls.Combobox?
【发布时间】:2015-07-16 11:19:57
【问题描述】:

我有一个组合框,但我发现我无法像这样设置 SelectedValue:

cmbA.SelectedValue = "asd"

所以我尝试这样做

cmbA.SelectedIndex = cmbA.FindString("asd");

基于How to set selected value from Combobox?

我意识到我的组合框是 System.Windows.Controls.ComboBox 而不是 System.Windows.Forms.ComboBox。

这意味着 FindString() 不可用。

基于User Control vs. Windows Form,我知道表单是控件的容器,但我不明白为什么 Controls.ComboBox 没有实现 FindString()。

我是否必须编写自己的代码来完成 FindString() 对 Forms.ComboBox 所做的工作?

【问题讨论】:

  • @siwmas SelectedValue 只有在 ComboBox 中没有这样的值时才会设置(SelectedItemSelectedIndex 也是如此),所以再次检查您的 @987654329 @ 实际上包含 "asd" 字符串作为其值之一。

标签: c# wpf combobox controls


【解决方案1】:

我不知道你想做什么,但我认为这样做会更容易

cmbA.Text = "String";

这样你就得到了你选择的项目

另外,我发现了一篇可以帮助您的有趣文章: Difference between SelectedItem, SelectedValue and SelectedValuePath

【讨论】:

    【解决方案2】:

    WPF ComboBoxes 与 WinForms 不同。它们可以显示对象的集合,而不仅仅是字符串。

    比如说,如果我有

    myComboBox.ItemsSource = new List<string> { "One", "Two", "Three" };
    

    我可以使用以下代码行来设置SelectedItem

    myComboBox.SelectedItem = "Two";
    

    我们不仅限于这里的字符串。我也可以说我想将我的 ComboBox 绑定到 List&lt;MyCustomClass&gt;,并且我想将 ComboBox.SelectedItem 设置为 MyCustomClass 对象。

    例如,

    List<MyCustomClass> data = new List<MyCustomClass> 
    { 
        new MyCustomClass() { Id = 1, Name = "One" },
        new MyCustomClass() { Id = 2, Name = "Two" },
        new MyCustomClass() { Id = 3, Name = "Three" }
    };
    myComboBox.ItemsSource = data;
    myComboBox.SelectedItem = data[0];
    

    我还可以告诉 WPF 我想将MyCustomClass 上的Id 属性视为标识属性,并且我想设置MyCombbox.SelectedValue = 2,它会知道找到带有@ 的MyCustomClass 对象987654332@属性为2,并将其设置为选中。

    myComboBox.SelectedValuePath = "Id";
    myComboBox.SelectedValue = 2;
    

    我什至可以将显示文本设置为使用不同的属性

    myComboBox.DisplayMemberPath = "Name";
    

    总而言之,WPF ComboBox 不仅可以处理字符串,而且由于功能扩展,不需要 FindString。您最有可能寻找的是将SelectedItem 设置为您的ItemsSource 集合中存在的对象之一。

    如果您不使用 ItemsSource,那么标准的 for-each 循环也应该可以工作

    foreach(ComboBoxItem item in myComboBox.Items)
    {
        if (item.Content == valueToFind)
            myComboBox.SelectedItem = item;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-11-02
      • 1970-01-01
      • 2018-05-24
      • 1970-01-01
      • 1970-01-01
      • 2011-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多