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