简体   繁体   English

C#WPF如何检查组合框项目是否包含在列表中<string>

[英]C# WPF how to check if combobox item is contained in a list<string>

I have a ComboBox named combo. 我有一个名为combo的ComboBox。 I added items manually, because I had trouble linking them directly. 我手动添加了项目,因为我无法直接链接它们。 Turned out I did not need to. 原来我不需要。 However, I want to be able to select an item from a dropdown list (ComboBox) and on button click to check if the selection is contained in a list string. 但是,我希望能够从下拉列表(ComboBox)中选择一个项目,然后单击按钮以检查所选内容是否包含在列表字符串中。

Here is what I mean: 这是我的意思:

XAML: XAML:

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

C# 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)
            {

            }

Since you are not binding values , you can use SelectionBoxItem 由于您没有绑定值,因此可以使用SelectionBoxItem

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

  }

If you are binding a list, 如果您要绑定列表,

You could do this, 你可以这样

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

  }

I'm not sure why you're coding it and adding it my hand. 我不确定为什么要编码并将其添加到我的手上。 The usual approach with WPF is to have your list in a ViewModel ( ObservableCollection is what is usually used), and then simply bind your ComboBox to it. WPF的常用方法是将您的列表放在ViewModel (通常使用ObservableCollection ),然后将您的ComboBox绑定到它。

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

From there, you can use the selected item, or whatever else tickles your fancy, and fool around with it. 从那里,您可以使用选定的项目,或其他使您喜欢的项目挠痒痒,然后到处乱逛。
You can use what both Sajeetharan and Adriano suggested, and you can also check for it upon change, and have your logic happen then, or update your gui ... The sky's the limit :) 您可以使用Sajeetharan和Adriano的建议,也可以在更改时进行检查,然后让您的逻辑发生,或者更新gui ...天空是极限:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM