0

Is there an equivalent to this in .NET :

<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select> 

I mean build a dropdownlist that uses string indexes for each option, instead of using numeric index. I browsed through all combobox's properties and I didn't find any way to do this.

Bach
  • 45
  • 8

2 Answers2

2

The answer is that no, there is no way to have a string index into an IEnumerable but you wouldn't do this anyways in WPF. There are two ways to get the selected item out of a combobox, SelectedIndex (which is always an int), and SelectedItem.

SelectedIndex isn't generally used, since you don't generally care about the index of the selected item, you care about the selected item itself, which is easily accessible by...

SelectedItem: Bind this property to an object of the collections type ("CarManufacturer" in your example) and now you automatically have the whole object, with no real reason to have a "string" index. You can use DisplayMemberPath to get the "nice" name to appear for each item.

<ComboBox SelectedItem={Binding SelectedManufacturer} DisplayMemberPath="Name" ItemsSource={Binding CarManufacturers}/>

There is also "SelectedValue" which returns that "Display" string for the selected item, but that is used even less frequently since the information it contains is not necessarily unique to an item in the backing collection, and so not very useful for retrieving said item. There are a few use cases that could take advantage of it though.

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
  • Thanks for your reply, you're right, actually I've tottaly forgotten that you can pass object as item in many wpf controls. And yes, no need to use string indexes in that case. – Bach Mar 18 '14 at 00:29
1

You can sort of do what you are asking, but not really.

A ComboBox in WPF has three properties:

  • SelectedIndex: This is an zero-based integer representing the index value of the selected item.
  • SelectedItem: This is the actual selected object in the sequence of bound objects.
  • SelectedValue/SelectedValuePath: These two properties are used in conjunction to point to a property on the bound objects.

See this question/answer for some good examples.


In your case, you could create a sequence of Tuple<string, string> (or any object that represents the pair) and bind that to the collection, then take advantage of the SelectedValue and the SelectedValuePath to get the one string value, while using DisplayMemberPath to display the other string value.

<ComboBox ItemsSource="{Binding Path=SomeCollection}"
          SelectedValue={Binding Path=SelectedOption}"
          SelectedValuePath="Item1"
          DisplayMemberPath="Item2" />
Community
  • 1
  • 1
myermian
  • 31,823
  • 24
  • 123
  • 215