Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate a ComboBox in XAML

Tags:

combobox

wpf

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?

like image 882
Sonhja Avatar asked Feb 27 '13 18:02

Sonhja


People also ask

What is a ComboBox XAML?

A ComboBox represents a selection control that combines a non-editable textbox and a drop-down list box that allows users to select an item from a list. It either displays the current selection or is empty if there is no selected item.

What is DisplayMemberPath?

DisplayMemberPath specifies the path to the display string property for each item. In your case, you'd set it to "Name" , not "{Binding Name}" .


1 Answers

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>
like image 87
Farhad Jabiyev Avatar answered Oct 27 '22 15:10

Farhad Jabiyev