Sonhja
Sonhja

Reputation: 8458

How to populate a ComboBox in XAML

I'm trying to populate a ComboBox with a pair of String, Value. I did it in code behind like this:

listCombos = new List<ComboBoxItem>();
item = new ComboBoxItem { Text = Cultures.Resources.Off, Value = "Off" };
listCombos.Add(item);
item = new ComboBoxItem { Text = Cultures.Resources.Low, Value = "Low" };
listCombos.Add(item);
item = new ComboBoxItem { Text = Cultures.Resources.Medium, Value = "Medium" };
listCombos.Add(item);
item = new ComboBoxItem { Text = Cultures.Resources.High, Value = "High" };
listCombos.Add(item);
combo.ItemsSource = listCombos;

ComboBoxItem:

public class ComboBoxItem
{
    public string Text { get; set; }
    public object Value { get; set; }

    public override string ToString()
    {
        return Text;
    }
}

As you can see, I'm inserting the Text value using my ResourceDictionary. But if I do it in this way, when I change language at runtime, the ComboBox content doesn't.

So I wanted to try to fill my ComboBox at the design (at XAML).

So my question is: how can I fill my ComboBox with a pair Text, Value like above?

Upvotes: 10

Views: 16464

Answers (1)

Farhad Jabiyev
Farhad Jabiyev

Reputation: 26665

You will use Tag, not Value in xaml. This would be like this:

<ComboBox>
     <ComboBoxItem Tag="L" IsSelected="True">Low</ComboBoxItem>
     <ComboBoxItem Tag="H">High</ComboBoxItem>
     <ComboBoxItem Tag="M">Medium</ComboBoxItem>
</ComboBox>

Upvotes: 15

Related Questions