一、使用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. C++_系列自学课程_第_8_课_指针和引用_《C++ Primer 第四版》

    C语言最富有迷幻色彩的部分当属指针部分,无论是指针的定义还是指针的意义都可算是C语言中最复杂的内容.指针不但提供给了程序员直接操作硬件部分的操作接口,还提供给了程序员更多灵活的用法.C++继承这一高效 ...

  2. Java之数组篇

    动手动脑,第六次Tutorial--数组 这次的Tutorial讲解了Java中如何进行数组操作,包括数组声明创建使用和赋值运算,写这篇文章的目的就是通过实际运用已达到对数组使用的更加熟练,下面是实践 ...

  3. 时钟周期,CPU周期,指令周期,CPU时间片

    从小到大来说:时钟周期,CPU周期,指令周期,CPU时间片 时钟周期:一个脉冲需要的时间,频率的倒数 CPU周期:读取一个指令节所需的时间 指令周期:读取并执行完一个指令所需的时间 CPU时间片:CP ...

  4. Redis常用五大数据类型

    1.String(字符串) string类型是二进制安全的.意思是redis的string可以包含任何数据.比如jpg图片或者序列化的对象 . string类型是Redis最基本的数据类型,一个red ...

  5. C#登入例子--第一个程序

    第一步:在数据库创建一个存放账号密码的表单 第二步:创建一个登入项目 拆分成三层: CS层: BLL层: DAL层: Common层: Web.config:

  6. 关于在线编辑器的选择:tinymce - nilcms

    一开始使用的是百度开发的编辑器:ueditor.使用方便,很容易就部署了.现在发现此编辑器也就做一些安全性的更新,而且对于这个编辑器也越来越不喜欢了. 1.臃肿.[1.4.3.3 PHP 版本].下载 ...

  7. TypeScript的4种编译方式

    1.手动编译 1.1.首先找到TypeScript的安装目录,我的在"C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0".

  8. 轻松掌握:JavaScript观察者模式

    观察者模式 观察者模式也叫"订阅者/发布者"模式,定义对象间的一种一对多的依赖关系,发布者可以向所有订阅者发布消息. 观察者模式被广泛地应用于JavaScript客户端编程中.所有 ...

  9. Handler.sendMessage 与 Handler.obtainMessage.sendToTarget比较

    原文地址: http://www.cnblogs.com/android007/archive/2012/05/10/2494766.html 话说在工作中第一次接触android 的Handler ...

  10. dede:field name='imgurls'不能二次使用的解决办法

    {dede:field name='imgurls' alt='图片输出区'}图片链接  [field:linkurl/]图片地址 [field:imgsrc/]{/dede:field} 这个标签不 ...