Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I populate a WPF combo box in XAML with all the items from a given enum?

Tags:

Say I have an enum with four values:

public enum CompassHeading {     North,     South,     East,     West } 

What XAML would be required to have a ComboBox be populated with these items?

<ComboBox ItemsSource="{Binding WhatGoesHere???}" /> 

Ideally I wouldn't have to set up C# code for this.

like image 740
Drew Noakes Avatar asked Feb 11 '09 18:02

Drew Noakes


People also ask

How do you add a ComboBox to XAML?

You can get or set the combo box's selected item by using the SelectedItem property, and get or set the index of the selected item by using the SelectedIndex property. You populate the ComboBox by adding objects directly to the Items collection or by binding the ItemsSource property to a data source.

How do I add a ComboBox item in WPF?

On button click event handler, we add the content of TextBox to the ComboBox by calling ComboBox. Items. Add method. Now if you enter text in the TextBox and click Add Item button, it will add contents of the TextBox to the ComboBox.


1 Answers

You can use the ObjectDataProvider to do this:

<ObjectDataProvider MethodName="GetValues"      ObjectType="{x:Type sys:Enum}" x:Key="odp">     <ObjectDataProvider.MethodParameters>         <x:Type TypeName="local:CompassHeading"/>     </ObjectDataProvider.MethodParameters> </ObjectDataProvider>  <ComboBox ItemsSource="{Binding Source={StaticResource odp}}" /> 

I found the solution here:

http://bea.stollnitz.com/blog/?p=28

like image 110
casperOne Avatar answered Oct 24 '22 18:10

casperOne