简体   繁体   中英

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

I have a ComboBox named combo. 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.

Here is what I mean:

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

            }

Since you are not binding values , you can use 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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