42

I'm used to doing things like

State.Items.Add(new ListItem { Text = "SomeState", Value = NumericIDofState });

Where State is a Listbox in ASP.NET.

How do i achieve the same with a WPF ComboBox? I do see a property called 'Content' in the ComboBoxItem object but how do i assign each item a value other than what's displayed to the user? Please help.

1
  • 1
    Could you check out my answer and see if it's more useful for future readers than the one you've accepted? Aug 27, 2020 at 19:00

4 Answers 4

79

WPF Combobox has:

  • SelectedValuePath property that specifies the path to the property that is used to determine the value of the SelectedValue property. It's similar to ASP.NET ListItem's Value property.
  • DisplayMemberPath property that defines a default template that describes how to display the data objects. It's similar to ASP.NET ListItem's Text property.

Let's say you want your Combobox to show a collection of the following KeyValuePair objects:

private static readonly KeyValuePair<int, string>[] tripLengthList = {
    new KeyValuePair<int, string>(0, "0"),
    new KeyValuePair<int, string>(30, "30"), 
    new KeyValuePair<int, string>(50, "50"), 
    new KeyValuePair<int, string>(100, "100"), 
};

You define a property in your view model returning that collection:

public KeyValuePair<int, string>[] TripLengthList
{
    get
    {
        return tripLengthList;
    }
}

Then, your XAML for the Combobox would be:

<ComboBox
    SelectedValue="{Binding FilterService.TripLengthFrom, Mode=TwoWay}"
    ItemsSource="{Binding TripLengthList, Mode=OneTime}"
    SelectedValuePath="Key"
    DisplayMemberPath="Value" />

Where you set SelectedValuePath and DisplayMemberPath properties to the desired property names of the objects (Key and Value correspondingly) displaying by the Combobox.

Or, if you really want to add items to Combobox in code behind instead of using a binding, you can do it as well. For example:

<!--XAML-->
<ComboBox x:Name="ComboBoxFrom"
    SelectedValue="{Binding FilterService.TripLengthFrom, Mode=TwoWay}" />

// Code behind
public partial class FilterView : UserControl
{
    public FilterView()
    {
        this.InitializeComponent();

        this.ComboBoxFrom.SelectedValuePath = "Key";
        this.ComboBoxFrom.DisplayMemberPath = "Value";
        this.ComboBoxFrom.Items.Add(new KeyValuePair<int, string>(0, "0"));
        this.ComboBoxFrom.Items.Add(new KeyValuePair<int, string>(30, "30"));
        this.ComboBoxFrom.Items.Add(new KeyValuePair<int, string>(50, "50"));
        this.ComboBoxFrom.Items.Add(new KeyValuePair<int, string>(100, "100"));
    }
3
  • 3
    I think this should be the chosen answer as it explains more on what can be done. Oct 13, 2018 at 21:42
  • 1
    Unfortunately, OP hasn't visited SO after the answer was posted, Still waiting for him. Sep 21, 2020 at 18:49
  • Note future WinUI 3 users: I needed to use an IValueConverter to get a similar thing working with integer binding.
    – AlgoRythm
    Mar 28 at 20:18
59

If you only want to expose a simple property in the viewmodel and handle the text for the choices in the view you can do a simple solution like this:

    <ComboBox SelectedValuePath="Tag" SelectedValue="{Binding YourIntProperty, Mode=TwoWay}">
        <ComboBoxItem Content="First choice" Tag="0"/>
        <ComboBoxItem Content="Second choice" Tag="1"/>
        <ComboBoxItem Content="Third choice" Tag="2"/>
    </ComboBox>

Example with a bool property:

    <ComboBox SelectedValuePath="Tag" SelectedValue="{Binding IsActive, Mode=TwoWay}">
        <ComboBoxItem Content="No" Tag="False"/>
        <ComboBoxItem Content="Yes" Tag="True"/>
    </ComboBox>

Type-verbose alternatives (original examples)

Below are more verbose alternatives where the types are explicitly declared. Depending on your preferred style (or maybe some types that requires it), maybe it suits you better.

<ComboBox SelectedValuePath="Tag" SelectedValue="{Binding YourIntProperty, Mode=TwoWay}">
    <ComboBoxItem Content="First choice">
        <ComboBoxItem.Tag>
            <sys:Int32>0</sys:Int32>
        </ComboBoxItem.Tag>
    </ComboBoxItem>
    <ComboBoxItem Content="Second choice">
        <ComboBoxItem.Tag>
            <sys:Int32>1</sys:Int32>
        </ComboBoxItem.Tag>
    </ComboBoxItem>
    <ComboBoxItem Content="Third choice">
        <ComboBoxItem.Tag>
            <sys:Int32>2</sys:Int32>
        </ComboBoxItem.Tag>
    </ComboBoxItem>
</ComboBox>

Example with a bool property:

<ComboBox SelectedValuePath="Tag" SelectedValue="{Binding IsActive, Mode=TwoWay}">
    <ComboBoxItem Content="No">
        <ComboBoxItem.Tag>
            <sys:Boolean>False</sys:Boolean>
        </ComboBoxItem.Tag>
    </ComboBoxItem>
    <ComboBoxItem Content="Yes">
        <ComboBoxItem.Tag>
            <sys:Boolean>True</sys:Boolean>
        </ComboBoxItem.Tag>
    </ComboBoxItem>
</ComboBox>

The sys namespace is declared as this:

xmlns:sys="clr-namespace:System;assembly=mscorlib"
4
  • 2
    great example with the boolean. just what i needed. i too dont like put all available UI strings (to select from) in my viewmodel, i want them in the XAML only.
    – Fredrik
    Oct 17, 2017 at 12:26
  • 1
    why not Tag="True"?
    – dovid
    Dec 10, 2017 at 12:16
  • 3
    @dovid thanks for the suggestion, I tested and it works. I have updated my answer with simplified examples, but keeping the old examples too in case needed for corner cases.
    – TGasdf
    Dec 15, 2017 at 10:50
  • 1
    To get the value of selected Tag use: string selectedTag=((ComboBoxItem)this.ComboBoxName.SelectedItem).Tag.ToString(); See stackoverflow.com/questions/6309495
    – intotecho
    Dec 3, 2020 at 0:27
28

See these properties of combo:

1
  • 25
    Please provide an example.
    – Demodave
    Oct 29, 2018 at 14:04
0

If you skip the Value, then I think it's quite simple to add a new item into a ComboBox during runtime.

comboBox1.Items.Add("SomeText");

comboBox1.SelectedIndex = comboBox1.Items.Count - 1;

The SelectedIndex property is set to Items.Count-1 so that the newly added item appears in the ComboBox as the selected item.

1
  • OP wants to know how to assign a value for each item displayed in the combobox/dropdown. This answer is talking about adding new items at runtime without regard to value, completely off point from what the question is asking. Nov 27, 2023 at 19:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.