You can do this by converting your Enum to a list of MyEnum tuples and using the DisplayMemberPath ListBox parameter to display the description element. When you select a specific Tuple, just take its MyEnum part and use this to set the SelectedEnumValue property to the ViewModel.
Here is the code:
XAML:
<Window x:Class="EnumToListBox.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <ListBox Grid.Row="0" ItemsSource="{Binding EnumToDescriptions}" SelectedItem="{Binding SelectedEnumToDescription}" DisplayMemberPath="Item2"/> <TextBlock Grid.Row="1" Text="{Binding SelectedEnumToDescription.Item2}"/> </Grid>
Code behind:
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.DataContext = new ViewModel(); } } public class ViewModel : PropertyChangedNotifier { private List<Tuple<MyEnum, string>> _enumToDescriptions = new List<Tuple<MyEnum, string>>(); private Tuple<MyEnum, string> _selectedEnumToDescription; public ViewModel() { Array Values = Enum.GetValues(typeof(MyEnum)); foreach (var Value in Values) { var attributes = Value.GetType().GetField(Value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false); var attribute = attributes[0] as DescriptionAttribute; _enumToDescriptions.Add(new Tuple<MyEnum, string>((MyEnum)Value, (string)attribute.Description)); } } public List<Tuple<MyEnum, string>> EnumToDescriptions { get { return _enumToDescriptions; } set { _enumToDescriptions = value; OnPropertyChanged("EnumToDescriptions"); } } public Tuple<MyEnum, string> SelectedEnumToDescription { get { return _selectedEnumToDescription; } set { _selectedEnumToDescription = value; SelectedEnumValue = _selectedEnumToDescription.Item1; OnPropertyChanged("SelectedEnumToDescription"); } } private MyEnum? _selectedEnumValue; public MyEnum? SelectedEnumValue { get { return _selectedEnumValue; } set { _selectedEnumValue = value; OnPropertyChanged("SelectedEnumValue"); } } } public enum MyEnum { [Description("Item1Description")] Item1, [Description("Item2Description")] Item2, [Description("Item3Description")] Item3, [Description("Item4Description")] Item4 } public class PropertyChangedNotifier : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string propertyName) { var propertyChanged = PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } }
source share