Dre*_*kes 22 .net data-binding wpf enums combobox
假设我有一个包含四个值的枚举:
public enum CompassHeading
{
North,
South,
East,
West
}
Run Code Online (Sandbox Code Playgroud)
使用这些项目填充ComboBox需要什么样的XAML?
<ComboBox ItemsSource="{Binding WhatGoesHere???}" />
Run Code Online (Sandbox Code Playgroud)
理想情况下,我不必为此设置C#代码.
cas*_*One 23
您可以使用ObjectDataProvider执行此操作:
<ObjectDataProvider MethodName="GetValues"
ObjectType="{x:Type sys:Enum}" x:Key="odp">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:CompassHeading"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
<ComboBox ItemsSource="{Binding Source={StaticResource odp}}" />
Run Code Online (Sandbox Code Playgroud)
我在这里找到了解决方案:
http://bea.stollnitz.com/blog/?p=28
Tho*_*que 14
我认为使用ObjectDataProvider来做这件事真的很乏味......我有一个更简洁的建议(是的,我知道,有点晚了......),使用标记扩展:
<ComboBox ItemsSource="{local:EnumValues local:EmployeeType}"/>
Run Code Online (Sandbox Code Playgroud)
以下是标记扩展的代码:
[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);
}
}
Run Code Online (Sandbox Code Playgroud)
以下是如何绑定到WPF中的枚举的详细示例
假设您有以下枚举
public enum EmployeeType
{
Manager,
Worker
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以在代码隐藏中绑定
typeComboBox.ItemsSource = Enum.GetValues(typeof(EmployeeType));
Run Code Online (Sandbox Code Playgroud)
或使用ObjectDataProvider
<ObjectDataProvider MethodName="GetValues" ObjectType="{x:Type sys:Enum}" x:Key="sysEnum">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:EmployeeType" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
Run Code Online (Sandbox Code Playgroud)
现在你可以在标记中绑定
<ComboBox ItemsSource="{Binding Source={StaticResource sysEnum}}" />
Run Code Online (Sandbox Code Playgroud)