using System;
using System.Globalization;
using System.Resources;
using System.Windows.Data;
public class CarColorConverter : IValueConverter
{
private static ResourceManager CarColors = new ResourceManager(typeof(Properties.CarColors));
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var key = ((Enum)value).ToString();
var result = CarColors.GetString(key);
if (result == null) {
result = key;
}
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum Output
{
// This will be hidden in the Output
None = -1,
[Description("Video")]
Video = 0,
[Description("Audio")]
Audio = 1
}
6条答案
按热度按时间a7qyws3x1#
是的,这是可能的。这样就行了。假设我们有枚举
然后我们可以将ObjectDataProvider用作
x一个一个一个一个x一个一个二个x
对于列表框,我们将ItemsSource设置为MyEnumValues,并使用Converter应用ItemTemplate。
在转换器中,我们获取描述并将其返回
GetEnumDescription方法可能应该放在其他地方,但您会得到这样的想法:)
检查GetEnumDescription as extension method。
gj3fmq9x2#
另一个解决方案是定制MarkupExtension,它从枚举类型生成项,这使得xaml更加紧凑和可读。
用法示例:
标记扩展实现
dddzy1tm3#
如果绑定到枚举,则可能通过IValueConverter将其转换为说明。
有关如何完成此操作的说明,请参见Binding ComboBoxes to enums... in Silverlight!。
有关详细信息,请参见http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx。
k4aesqcs4#
您可以在项目中定义资源文件(*. resx文件)。在该文件中,您必须定义"键-值对",如下所示:
等等...
keys等于你的enum-entries,类似于:
等等...
使用WPF时,可以在XAML代码中实现如下内容:
然后你必须编写你的转换器,类似这样:
我的回答迟了7年;- )但是也许它可以被别人使用!
jobtbby35#
嗯,有可能。
ListBox
可以帮助我们做到这一点,无需转换器。该方法的步骤如下:
创建一个列表框,将列表框的ItemsSource设置为枚举,并将列表框的SelectedItem绑定到selected属性。
然后将创建每个ListBoxItem。
*步骤1:定义枚举。
然后将以下属性添加到您的DataContext(或MVVM的ViewModel)中,该属性记录了选中的项目。
*步骤2:将枚举添加到Window、UserControl或Grid等的静态资源中。
*步骤3:使用列表框填充每个项目
参考文件:https://www.codeproject.com/Articles/130137/Binding-TextBlock-ListBox-RadioButtons-to-Enums
ruarlubt6#
来源:
这个anwser是基于Brian Lagunas' EnumBindingSourceExtension + EnumDescriptionTypeConverter的原始工作。我已经为它做了修改,以更好地适应我的需要。
我更改的内容:
1.使用布尔函数扩展了Enum类,该函数检查EnumValue是否具有[Description]属性
1.修改了"EnumDescriptionTypeConverter"中Brian的"ConvertTo()"函数,以便在未应用[Description]属性时返回"null"
1.通过调用我自己的函数编辑Brian的返回值,修改了"EnumBindingSourceExtension"中的"ProvideValue()"函数
添加我的函数来按索引对枚举进行排序(原始代码在跨项目时有问题..),并删除任何没有[Description]属性的值:
此示例已应用于组合框:
代码隐藏:
"转换预设"枚举和Picture of the ComboBox Rendered
"输出"枚举和Picture of the ComboBox Rendered