您可以通过将 Enum 转换为 MyEnum 字符串元组列表并使用 ListBox 的 DisplayMemberPath 参数来显示描述项来实现。当你选择一个特定的元组时,只需抓住它的 MyEnum 部分,并使用它来设置 ViewModel 中的 SelectedEnumValue 属性。
这是代码:
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>
代码隐藏:
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));
}
}
}