一、使用ObjectDataProvider

<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
SizeToContent="WidthAndHeight"
Title="Show Enums in a ListBox using Binding"> <Window.Resources>
<ObjectDataProvider MethodName="GetValues"
ObjectType="{x:Type sys:Enum}"
x:Key="AlignmentValues">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="HorizontalAlignment" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources> <Border Margin="10" BorderBrush="Aqua"
BorderThickness="3" Padding="8">
<StackPanel Width="300">
<TextBlock>Choose the HorizontalAlignment
value of the Button:</TextBlock>
<ListBox Name="myComboBox" SelectedIndex="0" Margin="8"
ItemsSource="{Binding Source={StaticResource
AlignmentValues}}"/>
<Button Content="Click Me!"
HorizontalAlignment="{Binding ElementName=myComboBox,
Path=SelectedItem}"/>
</StackPanel>
</Border>
</Window>

二、使用Converter

public class RadioButtonCheckedConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return value.Equals(parameter);
} public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return value.Equals(true) ? parameter : Binding.DoNothing;
}
}
使用方法:
<RadioButton GroupName="EnumGroup"
IsChecked="{Binding EnumProperty, Converter={StaticResource RadioButtonCheckedConverter},
ConverterParameter={x:Static src:TestEnum.Option1}}">
</RadioButton> <RadioButton GroupName="EnumGroup"
IsChecked="{Binding EnumProperty, Converter={StaticResource RadioButtonCheckedConverter},
ConverterParameter={x:Static src:TestEnum.Option2}}">
</RadioButton> <RadioButton GroupName="EnumGroup"
IsChecked="{Binding EnumProperty, Converter={StaticResource RadioButtonCheckedConverter},
ConverterParameter={x:Static src:TestEnum.Option3}}">
</RadioButton>
 

三、使用扩展的Markup

[MarkupExtensionReturnType(typeof(IEnumerable))]

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);

   }

}
 
使用方法:
<ListBox Name="myComboBox" SelectedIndex="0" Margin="8"

              ItemsSource="{my:EnumValues HorizontalAlignment}"/>

四、使用资源文件实现Enum本地化

为Enum类型自定义Attribute

从而实现Enum与资源关联

    /// <summary>
/// Attribute for localization.
/// </summary>
[AttributeUsage(AttributeTargets.All,Inherited = false,AllowMultiple = true)]
public sealed class LocalizableDescriptionAttribute : DescriptionAttribute
{
#region Public methods.
// ------------------------------------------------------------------ /// <summary>
/// Initializes a new instance of the
/// <see cref="LocalizableDescriptionAttribute"/> class.
/// </summary>
/// <param name="description">The description.</param>
/// <param name="resourcesType">Type of the resources.</param>
public LocalizableDescriptionAttribute
(string description,Type resourcesType) : base(description)
{
_resourcesType = resourcesType;
} #endregion #region Public properties. /// <summary>
/// Get the string value from the resources.
/// </summary>
/// <value></value>
/// <returns>The description stored in this attribute.</returns>
public override string Description
{
get
{
if (!_isLocalized)
{
ResourceManager resMan =
_resourcesType.InvokeMember(
@"ResourceManager",
BindingFlags.GetProperty | BindingFlags.Static |
BindingFlags.Public | BindingFlags.NonPublic,
null,
null,
new object[] { }) as ResourceManager; CultureInfo culture =
_resourcesType.InvokeMember(
@"Culture",
BindingFlags.GetProperty | BindingFlags.Static |
BindingFlags.Public | BindingFlags.NonPublic,
null,
null,
new object[] { }) as CultureInfo; _isLocalized = true; if (resMan != null)
{
DescriptionValue =
resMan.GetString(DescriptionValue, culture);
}
} return DescriptionValue;
}
}
#endregion #region Private variables. private readonly Type _resourcesType;
private bool _isLocalized; #endregion
}

实现自定义的Converter

    /// <summary>
/// This class simply takes an enum and uses some reflection to obtain
/// the friendly name for the enum. Where the friendlier name is
/// obtained using the LocalizableDescriptionAttribute, which holds the localized
/// value read from the resource file for the enum
/// </summary>
[ValueConversion(typeof(object), typeof(String))]
public class EnumToFriendlyNameConverter : IValueConverter
{
#region IValueConverter implementation /// <summary>
/// Convert value for binding from source object
/// </summary>
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
// To get around the stupid WPF designer bug
if (value != null)
{
FieldInfo fi = value.GetType().GetField(value.ToString()); // To get around the stupid WPF designer bug
if (fi != null)
{
var attributes =
(LocalizableDescriptionAttribute[])
fi.GetCustomAttributes(typeof
(LocalizableDescriptionAttribute), false); return ((attributes.Length > 0) &&
(!String.IsNullOrEmpty(attributes[0].Description)))
?
attributes[0].Description
: value.ToString();
}
} return string.Empty;
} /// <summary>
/// ConvertBack value from binding back to source object
/// </summary>
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new Exception("Cant convert back");
}
#endregion
}

使用方法:

<ComboBox x:Name="cmbFoodType"
ItemsSource="{Binding Source={StaticResource foodData}}"
SelectedItem="{Binding Path=TestableClass.FoodType, Mode=TwoWay}" Height="Auto">
<ComboBox.ItemTemplate> <DataTemplate>
<Label Content="{Binding Path=.,Mode=OneWay,
Converter={StaticResource enumItemsConverter}}"
Height="Auto"
Margin="0"
VerticalAlignment="Center"/> </DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>

参考

Binding and Using Friendly Enums in WPF

Displaying Enum Values using Data Binding

Binding Radio Buttons to a Single Property

WPF -Enum的三种绑定方法的更多相关文章

  1. 用Visual C++创建WPF项目的三种主要方法

    用Visual C++创建WPF项目的三种主要方法 The problem with using XAML from C++ Because C++ doesn't support partial c ...

  2. JS面向对象(3) -- Object类,静态属性,闭包,私有属性, call和apply的使用,继承的三种实现方法

    相关链接: JS面向对象(1) -- 简介,入门,系统常用类,自定义类,constructor,typeof,instanceof,对象在内存中的表现形式 JS面向对象(2) -- this的使用,对 ...

  3. C#使用DataSet Datatable更新数据库的三种实现方法

    本文以实例形式讲述了使用DataSet Datatable更新数据库的三种实现方法,包括CommandBuilder 方法.DataAdapter 更新数据源以及使用sql语句更新.分享给大家供大家参 ...

  4. JavaScript 三种绑定事件方式之间的区别

    JavaScript三种绑定事件的方式: 1. <div id="btn" onclick="clickone()"></div> // ...

  5. Binding 中 Elementname,Source,RelativeSource 三种绑定的方式

    在WPF应用的开发过程中Binding是一个非常重要的部分. 在实际开发过程中Binding的不同种写法达到的效果相同但事实是存在很大区别的. 这里将实际中碰到过的问题做下汇总记录和理解. 1. so ...

  6. Liunx 环境下vsftpd的三种实现方法(超详细参数)

    以下文章介绍Liunx 环境下vsftpd的三种实现方法 ftp://vsftpd.beasts.org/users/cevans/vsftpd-2.0.3.tar.gz,目前已经到2.0.3版本.假 ...

  7. Android开发 ---Button的OnClickListener的三种实现方法

    button的OnClickListener的三种实现方法 onclick事件的定义方法,分为三种,分别为 1.在xml中进行指定方法: 2.在Actitivy中new出一个OnClickListen ...

  8. JavaScript三种绑定事件的方式

    JavaScript三种绑定事件的方式: 1. <div id="btn" onclick="clickone()"></div> // ...

  9. Dom事件的三种绑定方式

    1.事件 2.  onclick, onblur, onfocus, 需求:请写出一个行为,样式,结构,相分离的页面.   JS,   CSS,  HTML, 示例1,行为结构样式粘到一起的页面: & ...

随机推荐

  1. WPF阴影效果(DropShadowEffect)

    <TextBlock Text="阴影效果" FontSize="32"> <TextBlock.Effect> <DropSha ...

  2. [Asp.net 5] DependencyInjection项目代码分析4-微软的实现(5)(IEnumerable<>补充)

    Asp.net 5的依赖注入注入系列可以参考链接: [Asp.net 5] DependencyInjection项目代码分析-目录 我们在之前讲微软的实现时,对于OpenIEnumerableSer ...

  3. C#使用资源文件的方法

    其实,对于资源文件的使用,说白点就是通过强制类型转换,将资源文件里的数据强行的转换成你需要的(换种方式说,就是你原来存进去什么,就用什么类型拿出来). 主要通过System.Resources.Res ...

  4. error when loading the sdk error parsing

    Error Parsing: C:\android-sdk_r24.2-windows\android-sdk-windows\system-images\android-22\android-wea ...

  5. OA项目——总结

    先来张大致结构图: 项目链接:https://github.com/shuai7boy/YM_OA

  6. 【linux草鞋应用编程系列】_2_ 环境变量和进程控制

    一. 环境变量     应用程序在执行的时候,可能需要获取系统的环境变量,从而执行一些相应的操作.     在linux中有两种方法获取环境变量,分述如下.   1.通过main函数的参数获取环境变量 ...

  7. Cursor的用法

    文章主要来自于::::http://www.cnblogs.com/TerryBlog/archive/2010/07/05/1771459.html 主要为了自己学习方便,侵删!!!! 使用过 SQ ...

  8. ERROR LazyInitializationException:19 - failed to lazily initialize a collection of role: com.goodfan.entity.BeanA.beanB, no session or session was closed

    1. 问题, 当使用JSONArray.fromObject(List<BeanA>)时, beanA中含有BeanB的属性beanB时,会报这个错 2. 解决办法: 使用jsonconf ...

  9. java反编译获取源码

    最近在研究反射,想做一个东西,把运行的java程序饭编译(Decompile)成.java文件.现思路如下: 1.写出程序反编译一个类 2.将所有类反编译 3.java代码注入一个正在运行的java程 ...

  10. [翻译] Autoac 最佳实践和建议

    使用嵌套的 ILifetimeScope 解析服务 Autofac 被设计为跟踪(track)和清理(dispose)资源.为确保资源被正确处理,务必将长时间运行的应用程序分成小的工作单元 (请求或事 ...