Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is how I am doing it with MVVM. On my model I would have defined my enum:</p> <pre><code> public enum VelocityUnitOfMeasure { [Description("Miles per Hour")] MilesPerHour, [Description("Kilometers per Hour")] KilometersPerHour } </code></pre> <p>On my ViewModel I expose a property that provides possible selections as string as well as a property to get/set the model's value. This is useful if we don't want to use every enum value in the type:</p> <pre><code> //UI Helper public IEnumerable&lt;string&gt; VelocityUnitOfMeasureSelections { get { var units = new [] { VelocityUnitOfMeasure.MilesPerHour.Description(), VelocityUnitOfMeasure.KilometersPerHour.Description() }; return units; } } //VM property public VelocityUnitOfMeasure UnitOfMeasure { get { return model.UnitOfMeasure; } set { model.UnitOfMeasure = value; } } </code></pre> <p>Furthermore, I use a generic EnumDescriptionCoverter:</p> <pre><code>public class EnumDescriptionConverter : IValueConverter { //From Binding Source public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (!(value is Enum)) throw new ArgumentException("Value is not an Enum"); return (value as Enum).Description(); } //From Binding Target public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (!(value is string)) throw new ArgumentException("Value is not a string"); foreach(var item in Enum.GetValues(targetType)) { var asString = (item as Enum).Description(); if (asString == (string) value) { return item; } } throw new ArgumentException("Unable to match string to Enum description"); } } </code></pre> <p>And finally, with the view I can do the following:</p> <pre><code>&lt;Window.Resources&gt; &lt;ValueConverters:EnumDescriptionConverter x:Key="enumDescriptionConverter" /&gt; &lt;/Window.Resources&gt; ... &lt;ComboBox SelectedItem="{Binding UnitOfMeasure, Converter={StaticResource enumDescriptionConverter}}" ItemsSource="{Binding VelocityUnitOfMeasureSelections, Mode=OneWay}" /&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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