How to populate a ComboBox in XAML

15,673

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>
Share:
15,673
Sonhja
Author by

Sonhja

Partially programmer, partially designer! An WPF lover, Android developer and .Net contributor! Learning more and more everyday :) And happy to help others work!

Updated on July 19, 2022

Comments

  • Sonhja
    Sonhja almost 2 years

    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?

  • Sonhja
    Sonhja about 11 years
    That was exactly the solution! Thanks! :)