在WPF中如何将Enum 绑定到 集合控件?

今日Google这个问题,呀,还真的在国外发现许多解决方法,其中经典的有:

 第一种,通过绑定转换器:

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() 
 
} 
} 

 

XAML

<local:EnumToNamesConverter x:Key="EnumToNamesConverter" />

 

<ComboBox ItemsSource="{Binding 
                        Source={x:Type local:CompassHeading}, 
                        Converter={StaticResource EnumToNamesConverter}}"
/> 

第二种,经典呀!通过继承MarkupExtension

 

[MarkupExtensionReturnType(typeof(object[]))] 
public class EnumValuesExtension : MarkupExtension 
{ 
   
public EnumValuesExtension() 
   
{ 
   
} 
 
   
public EnumValuesExtension(Type enumType) 
   
{ 
       
this.EnumType = enumType; 
   
} 
 
   
[ConstructorArgument("enumType")] 
   
public Type EnumType { get; set; } 
 
   
public override object ProvideValue(IServiceProvider serviceProvider) 
   
{ 
       
if (this.EnumType == null) 
           
throw new ArgumentException("The enum type is not set"); 
       
return Enum.GetValues(this.EnumType); 
   
} 
} 


XAML

<ComboBox ItemsSource="{local:EnumValues local:EmployeeType}"/> 

 

 

转载于:https://www.cnblogs.com/sofire/archive/2010/03/19/1690111.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值