Reputation: 33
I've searched for answers to this for a while, but none seem to match my problem exactly.
I have a window in which I've created a ComboBox
. Then in my code, I've created an array:
public string[] myList = new[] { "Item 1", "Item 2" };
Now I want to make those items the options in the ComboBox
dropdown. Most of what I found suggests using DataSource
and DataBind
, but only DataContext
is actually available.
I'm sure there's some previous step I'm missing, but I'm still pretty new to this so I'm not sure what it is.
Upvotes: 1
Views: 3389
Reputation: 60
try putting ID's with mapped to each member of the string list. It will work.
Upvotes: 0
Reputation: 25341
Those answers that you found are for Winforms and you seem to be using WPF. They both have a ComboBox
control, but they are actually a completely different controls with different properties. Try this (let's say you call it ComboBox1
):
ComboBox1.ItemsSource = myList;
However, you usually need IDs for your items so you can use them when the user selects an item. To do that, you need to bind the ComboBox
to a Dictionary
instead of a List
, like this:
var data = new Dictionary<int, string>{
{100, "Eggplant"},
{102, "Onion"},
{300, "Potato"},
{105, "Tomato"},
{200, "Zuccini"}
};
ComboBox1.ItemsSource = data;
ComboBox1.DisplayMemberPath = "Value";
ComboBox1.SelectedValuePath = "Key";
Now when a user selects "Onion" for example, you will get 102 by using:
int selected = (int)ComboBox1.SelectedValue;
Note: Your ComboBox1
in XAML must have no items, otherwise you will get an error.
If you prefer to keep the items in XAML instead of code-behind, there is no equivalent to the SelectedValuePath
property, but you can simulate it using the Tag
property like this:
<ComboBox x:Name="ComboBox1" SelectedValuePath="Tag">
<ComboBoxItem Content="Eggplant" Tag="100" />
<ComboBoxItem Content="Onion" Tag="102" />
<ComboBoxItem Content="Potato" Tag="300" />
<ComboBoxItem Content="Tomato" Tag="105" />
<ComboBoxItem Content="Zuccini" Tag="200" />
</ComboBox>
Upvotes: 4