Giải pháp thứ ba:
Đây là công việc tăng thêm một chút, tốt hơn là dễ dàng hơn trong thời gian dài nếu bạn đang ràng buộc tải trọng của Enums. Sử dụng một Trình biến đổi lấy kiểu liệt kê làm một tham số và chuyển đổi nó thành một chuỗi các chuỗi như là một đầu ra.
Trong VB.NET:
Public Class EnumToNamesConverter
Implements IValueConverter
Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
Return [Enum].GetNames(DirectCast(value, Type))
End Function
Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
Throw New NotImplementedException()
End Function
End Class
Hoặc trong C#:
public sealed class EnumToNamesConverter : IValueConverter
{
object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return Enum.GetNames(value.GetType());
}
object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw New NotSupportedException()
}
}
Sau đó, trong Application.xaml
của bạn, thêm một nguồn lực toàn cầu để truy cập chuyển đổi này:
<local:EnumToNamesConverter x:Key="EnumToNamesConverter" />
Cuối cùng sử dụng bộ chuyển đổi trong bất kỳ trang XAML nào mà bạn cần các giá trị của bất kỳ Enum nào ...
<ComboBox ItemsSource="{Binding
Source={x:Type local:CompassHeading},
Converter={StaticResource EnumToNamesConverter}}" />
Tôi vừa đọc bài viết gần đây của Eric Burke về một lớp Swing JComboBox thực hiện điều này, và nghĩ "Này, tôi thề tôi đã thấy một câu hỏi SO về điều này ..." Tôi đã gần, nhưng bạn muốn WPF, chứ không phải Java/Swing . Dù sao, ở đây nó là dành cho hậu thế: http://stuffthathappens.com/blog/2009/02/10/a-swing-jcombobox-for-enums/ – JMD