【问题标题】:C# WPF how to check if combobox item is contained in a list<string>C#WPF如何检查组合框项目是否包含在列表中
【发布时间】:2014-09-08 10:24:18
【问题描述】:

我有一个名为 combo 的 ComboBox。 我手动添加了项目,因为我无法直接链接它们。原来我不需要。 但是,我希望能够从下拉列表(组合框)中选择一个项目,然后单击按钮以检查选择是否包含在列表字符串中。

这就是我的意思:

XAML:

    <ComboBox Name="combo"/>
            <ComboBoxItem Content="Aa"/>
            <ComboBoxItem Content="Ba"/>
            <ComboBoxItem Content="Ca"/>   
    </ComboBox>

C#

    //list

    string a = "Aa";
    string b = "Ba";
    string c = "Ca";

    List<string> list = new List<string>();
    list.Add(a);
    list.Add(b);
    list.Add(c);

    //button

     private void Button_Click_1(object sender, RoutedEventArgs e)
            {

            }

【问题讨论】:

    标签: c# wpf list xaml combobox


    【解决方案1】:

    我不确定您为什么要对其进行编码并将其添加到我的手中。 WPF 的常用方法是将您的列表放在ViewModel 中(ObservableCollection 是常用的),然后简单地将您的ComboBox 绑定到它。

    <ComboBox Name = "combo" ItemsSource="{Binding YourCollectionNameHere}" 
              SelectedItem="{Binding YourStringProperty}"
    />
    

    从那里,您可以使用选定的项目,或其他任何您喜欢的东西,然后玩弄它。
    您可以使用 Sajeetharan 和 Adriano 的建议,也可以在更改时检查它,然后让您的逻辑发生,或者更新您的 gui... 没有限制 :)

    【讨论】:

      【解决方案2】:

      由于你没有绑定值,你可以使用SelectionBoxItem

       if (list.Contains(combo.SelectionBoxItem.ToString()))
        { 
      
        }
      

      如果你要绑定一个列表,

      你可以这样做,

        if (list.Contains(Combobox.SelectedItem.ToString())))
        {
      
        }
      

      【讨论】:

      • 我认为 OP 的意思是所选项目是否包含在列表中(而不是其文本是否包含在此类列表的任何项目中)。在代码中:if (list.Contains(combo.SelectedItem.ToString()))
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-02
      • 2022-12-06
      • 2023-03-26
      • 2012-08-26
      相关资源
      最近更新 更多