WPF - add static items to a combo box

WpfXamlCombobox

Wpf Problem Overview


I've said it before and I'll say it again, the easiest examples for WPF are also the hardest to find on the web :)

I have a combo box that I need to display but it doesn't need to be databound or anything else, the content is static. How can I add a static list of items to my combo box using XAML?

Wpf Solutions


Solution 1 - Wpf

Here is the code from MSDN and the link - Article Link, which you should check out for more detail.

<ComboBox Text="Is not open">
    <ComboBoxItem Name="cbi1">Item1</ComboBoxItem>
    <ComboBoxItem Name="cbi2">Item2</ComboBoxItem>
    <ComboBoxItem Name="cbi3">Item3</ComboBoxItem>
</ComboBox>

Solution 2 - Wpf

Like this:

<ComboBox Text="MyCombo">
<ComboBoxItem  Name="cbi1">Item1</ComboBoxItem>
<ComboBoxItem  Name="cbi2">Item2</ComboBoxItem>
<ComboBoxItem  Name="cbi3">Item3</ComboBoxItem>
</ComboBox>

Solution 3 - Wpf

You can also add items in code:

cboWhatever.Items.Add("SomeItem");

Also, to add something where you control display/value, (almost categorically needed in my experience) you can do so. I found a good stackoverflow reference here:

https://stackoverflow.com/questions/8521152/key-value-pair-combobox-in-wpf

Sum-up code would be something like this:

ComboBox cboSomething = new ComboBox();
cboSomething.DisplayMemberPath = "Key";
cboSomething.SelectedValuePath = "Value";
cboSomething.Items.Add(new KeyValuePair<string, string>("Something", "WhyNot"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Deus", "Why"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Flirptidee", "Stuff"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Fernum", "Blictor"));

Solution 4 - Wpf

<ComboBox Text="Something">
			<ComboBoxItem Content="Item1"></ComboBoxItem >
			<ComboBoxItem Content="Item2"></ComboBoxItem >
			<ComboBoxItem Content="Item3"></ComboBoxItem >
</ComboBox>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionUnknown CoderView Question on Stackoverflow
Solution 1 - WpfWade73View Answer on Stackoverflow
Solution 2 - WpfTony The LionView Answer on Stackoverflow
Solution 3 - WpfomJohn8372View Answer on Stackoverflow
Solution 4 - Wpfritesh sethView Answer on Stackoverflow