一、使用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. 基于.net mvc 的供应链管理系统(YB-SCM)开发随笔

    作为园子里的伪新人,经常拜读众位大牛的帖子,一直有写点东西的想法. 今天终于下定决心去写这个系统的开发过程,由于本人文笔有限,不足之处多多海涵.

  2. HDU 5475(2015 ICPC上海站网络赛)--- An easy problem(线段树点修改)

    题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=5475 Problem Description One day, a useless calculato ...

  3. 圆形背景的TextView

    [应用场景]: [需要的xml]:shape_circle.xml <?xml version="1.0" encoding="UTF-8"?>&l ...

  4. SpringMVC解决乱码

    SpringMVC解决乱码 在web.xml中配置如下代码

  5. servlet/filter/listener/interceptor区别与联系

    转自:http://www.cnblogs.com/doit8791/p/4209442.html servlet.filter.listener是配置到web.xml中(web.xml 的加载顺序是 ...

  6. 那些过目不忘的H5页面

    原文链接:http://isux.tencent.com/great-mobile-h5-pages.html 从引爆朋友圈的H5小游戏<围住神经猫>,到颠覆传统广告的大众点评H5专题页& ...

  7. SharePoint 2013 定制搜索显示模板

    前言 之前我们已经介绍了一些关于搜索的相关配置,当然,用户关于搜索的要求可能是各种各样.有时候,用户会说,你们的显示结果太Low了,确实是:不过,在SharePoint中,我们可以很容易的定制搜索结果 ...

  8. JAVA静态代理模式(从现实生活角度理解代码原理)

    代理模式(Proxy):为其他对象提供一种代理以控制对这个对象的访问. 代理模式说白了就是"真实对象"的代表,在访问对象时引入一定程度的间接性,因为这种间接性可以附加多种用途. 在 ...

  9. iOS 中常用的对密码进行MD5加密

    iOS中MD5加密 标签(空格分隔): iOS MD5 + (NSString *)MD5:(NSString *)str { const char *cStr = [str UTF8String]; ...

  10. CSS3 新怎的伪类选择器

    :first-of-type p:first-of-type 选择属于其父元素的首个 <p> 元素的每个 <p> 元素. :last-of-type p:last-of-typ ...