LabelledValue - canton7/Stylet GitHub Wiki

Sometimes you want to display some object to the user, but you want to associate a custom (string) label with it, which will be displayed by your View. So you create a quick class to wrap up your object and attach this label.

Then you'll want to override ToString so that your View displays just the label, and Equals and GetHashCode so they work properly with things that have a SelectedItem of some sort (e.g. ComboBox). Finally, you'll want to implement INotifyPropertyChanged so that changes to this can be picked up by the View.

This is all that LabelledValue<T> is - a class with a string Label property and a T Value property. Plus an overridden ToString, GetHashCode, Equals, and implementing INotifyPropertyChanged.

For example:

public enum MyEnum
{
   Foo,
   Bar,
   Baz
}

class MyViewModel
{
   // Implement INotifyPropertyChanged if you want
   public BindableCollection<LabelledValue<MyEnum>> EnumValues { get; private set; }
   public LabelledValue<MyEnum> SelectedEnumValue { get; set; }

   public MyViewModel()
   {
      this.EnumValues = new BindableCollection<LabelledValue<MyEnum>>()
      {
         LabelledValue.Create("Foo Value", MyEnum.Foo),
         LabelledValue.Create("Bar Value", MyEnum.Bar),
         LabelledValue.Create("Baz Value", MyEnum.Baz),
      };

      this.SelectedEnumValue = this.EnumValues[0];
   }
}

Then your view...

<ComboBox ItemsSource="{Binding EnumValues}" SelectedItem="{Binding SelectedEnumValue}"/>
⚠️ **GitHub.com Fallback** ⚠️