[更新] 我回答的关键点是枚举值被完全转换了。我认为这种方法比每个枚举值都转换要容易。[/更新]
我需要在xaml中使用这个转换器吗,这样不仅下拉列表,显示的值也会有这种格式吗?
在ComboBox的Binding ItemsSource处(ItemsSource="{Binding Source={x:Null}, Converter={StaticResource converter}}"
),请检查以下代码。
我需要实现ConvertBack吗?
不需要,因为在运行时您无法修改枚举,即使可以,您也无法在VIEW中更改ComboBox的ItemsSource,这意味着Binding Mode是OneWay。
XAML
<Window x:Class="WpfApplication2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication2"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:MyEnumConverter x:Key="converter"/>
</Window.Resources>
<StackPanel>
<ComboBox ItemsSource="{Binding Source={x:Null}, Converter={StaticResource converter}, Mode=OneWay}"></ComboBox>
</StackPanel>
</Window>
代码
public enum MyEnum
{
HomeRun, StolenBase, FirstBase
}
[ValueConversion(typeof(object), typeof(List<string>))]
public class MyEnumConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var names = Enum.GetNames(typeof (MyEnum)).ToArray();
return names;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}