第三种解决方案:
这需要更多的前期工作,如果您绑定到大量枚举,从长远来看会更容易。使用以枚举类型为参数的转换器,并将其转换为字符串数组作为输出。
在 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
或者在 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()
}
}
然后在你的Application.xaml 中,添加一个全局资源来访问这个转换器:
<local:EnumToNamesConverter x:Key="EnumToNamesConverter" />
最后在需要任何 Enum 值的任何 XAML 页面中使用转换器...
<ComboBox ItemsSource="{Binding
Source={x:Type local:CompassHeading},
Converter={StaticResource EnumToNamesConverter}}" />