Note that there are some explanatory texts on larger screens.

plurals
  1. PODatabinding an enum property to a ComboBox in WPF
    text
    copied!<p>As an example take the following code:</p> <pre><code>public enum ExampleEnum { FooBar, BarFoo } public class ExampleClass : INotifyPropertyChanged { private ExampleEnum example; public ExampleEnum ExampleProperty { get { return example; } { /* set and notify */; } } } </code></pre> <p>I want a to databind the property ExampleProperty to a ComboBox, so that it shows the options "FooBar" and "BarFoo" and works in mode TwoWay. Optimally I want my ComboBox definition to look something like this:</p> <pre><code>&lt;ComboBox ItemsSource="What goes here?" SelectedItem="{Binding Path=ExampleProperty}" /&gt; </code></pre> <p>Currently I have handlers for the ComboBox.SelectionChanged and ExampleClass.PropertyChanged events installed in my Window where I do the binding manually.</p> <p>Is there a better or some kind of canonical way? Would you usually use Converters and how would you populate the ComboBox with the right values? I don't even want to get started with i18n right now.</p> <p><strong>Edit</strong></p> <p>So one question was answered: How do I populate the ComboBox with the right values.</p> <p>Retrieve Enum values as a list of strings via an ObjectDataProvider from the static Enum.GetValues method:</p> <pre><code>&lt;Window.Resources&gt; &lt;ObjectDataProvider MethodName="GetValues" ObjectType="{x:Type sys:Enum}" x:Key="ExampleEnumValues"&gt; &lt;ObjectDataProvider.MethodParameters&gt; &lt;x:Type TypeName="ExampleEnum" /&gt; &lt;/ObjectDataProvider.MethodParameters&gt; &lt;/ObjectDataProvider&gt; &lt;/Window.Resources&gt; </code></pre> <p>This I can use as an ItemsSource for my ComboBox:</p> <pre><code>&lt;ComboBox ItemsSource="{Binding Source={StaticResource ExampleEnumValues}}"/&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload