我试图找到一个简单的例子,枚举显示为是。我所看到的所有示例都试图添加好看的显示字符串,但我不想要那种复杂性。

基本上,我有一个类,通过首先将DataContext设置为这个类,然后在xaml文件中指定绑定,保存我绑定的所有属性:

<ComboBox ItemsSource="{Binding Path=EffectStyle}"/>

但这不会在组合框中显示枚举值作为项。


当前回答

上面所有的帖子都忽略了一个简单的技巧。可以从SelectedValue的绑定中找到如何自动地填充ItemsSource,以便您的XAML标记是正确的。

<Controls:EnumComboBox SelectedValue="{Binding Fool}"/>

例如,在ViewModel中

public enum FoolEnum
    {
        AAA, BBB, CCC, DDD

    };


    FoolEnum _Fool;
    public FoolEnum Fool
    {
        get { return _Fool; }
        set { ValidateRaiseAndSetIfChanged(ref _Fool, value); }
    }

ValidateRaiseAndSetIfChanged是我的INPC钩子。你的可能不同。

EnumComboBox的实现如下所示,但首先我需要一个小助手来获取我的枚举字符串和值

    public static List<Tuple<object, string, int>> EnumToList(Type t)
    {
        return Enum
            .GetValues(t)
            .Cast<object>()
            .Select(x=>Tuple.Create(x, x.ToString(), (int)x))
            .ToList();
    }

和主类(注意,我使用ReactiveUI通过WhenAny钩子属性更改)

using ReactiveUI;
using ReactiveUI.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Windows;
using System.Windows.Documents;

namespace My.Controls
{
    public class EnumComboBox : System.Windows.Controls.ComboBox
    {
        static EnumComboBox()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(EnumComboBox), new FrameworkPropertyMetadata(typeof(EnumComboBox)));
        }

        protected override void OnInitialized( EventArgs e )
        {
            base.OnInitialized(e);

            this.WhenAnyValue(p => p.SelectedValue)
                .Where(p => p != null)
                .Select(o => o.GetType())
                .Where(t => t.IsEnum)
                .DistinctUntilChanged()
                .ObserveOn(RxApp.MainThreadScheduler)
                .Subscribe(FillItems);
        }

        private void FillItems(Type enumType)
        {
            List<KeyValuePair<object, string>> values = new List<KeyValuePair<object,string>>();

            foreach (var idx in EnumUtils.EnumToList(enumType))
            {
                values.Add(new KeyValuePair<object, string>(idx.Item1, idx.Item2));
            }

            this.ItemsSource = values.Select(o=>o.Key.ToString()).ToList();

            UpdateLayout();
            this.ItemsSource = values;
            this.DisplayMemberPath = "Value";
            this.SelectedValuePath = "Key";

        }
    }
}

您还需要在Generic中正确设置样式。XAML或者你的盒子不会渲染任何东西,你会抓狂的。

<Style TargetType="{x:Type local:EnumComboBox}" BasedOn="{StaticResource {x:Type ComboBox}}">
</Style>

就是这样。这显然可以扩展到支持i18n,但会使帖子更长。

其他回答

简单明了的解释: http://brianlagunas.com/a-better-way-to-data-bind-enums-in-wpf/

xmlns:local="clr-namespace:BindingEnums"
xmlns:sys="clr-namespace:System;assembly=mscorlib"

...

<Window.Resources>
    <ObjectDataProvider x:Key="dataFromEnum" MethodName="GetValues"
                        ObjectType="{x:Type sys:Enum}">
        <ObjectDataProvider.MethodParameters>
            <x:Type TypeName="local:Status"/>
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
</Window.Resources>

...

<Grid>
    <ComboBox HorizontalAlignment="Center" VerticalAlignment="Center" MinWidth="150"
              ItemsSource="{Binding Source={StaticResource dataFromEnum}}"/>
</Grid>

我使用MarkupExtension的另一种解决方案。

I made class which provides items source: public class EnumToItemsSource : MarkupExtension { private readonly Type _type; public EnumToItemsSource(Type type) { _type = type; } public override object ProvideValue(IServiceProvider serviceProvider) { return Enum.GetValues(_type) .Cast<object>() .Select(e => new { Value = (int)e, DisplayName = e.ToString() }); } } That's almost all... Now use it in XAML: <ComboBox DisplayMemberPath="DisplayName" ItemsSource="{persons:EnumToItemsSource {x:Type enums:States}}" SelectedValue="{Binding Path=WhereEverYouWant}" SelectedValuePath="Value" /> Change 'enums:States' to your enum

我只是保持简单。我在ViewModel中创建了一个枚举值的项目列表:

public enum InputsOutputsBoth
{
    Inputs,
    Outputs,
    Both
}

private IList<InputsOutputsBoth> _ioTypes = new List<InputsOutputsBoth>() 
{ 
    InputsOutputsBoth.Both, 
    InputsOutputsBoth.Inputs, 
    InputsOutputsBoth.Outputs 
};

public IEnumerable<InputsOutputsBoth> IoTypes
{
    get { return _ioTypes; }
    set { }
}

private InputsOutputsBoth _selectedIoType;

public InputsOutputsBoth SelectedIoType
{
    get { return _selectedIoType; }
    set
    {
        _selectedIoType = value;
        OnPropertyChanged("SelectedIoType");
        OnSelectionChanged();
    }
}

在我的xaml代码中,我只需要这个:

<ComboBox ItemsSource="{Binding IoTypes}" SelectedItem="{Binding SelectedIoType, Mode=TwoWay}">

通用应用程序的工作方式似乎有点不同;它不具备全功能XAML的所有功能。对我有用的是:

我创建了一个枚举值列表作为enum(未转换为 字符串或整数),并将ComboBox ItemsSource绑定到它 然后我可以将ComboBox ItemSelected绑定到我的公共属性 枚举的类型是谁

只是为了好玩,我创建了一个小模板类来帮助解决这个问题,并将其发布到MSDN Samples页面。额外的位可以让我有选择地覆盖枚举的名称,并让我隐藏一些枚举。我的代码看起来很像Nick的(上面),我希望我能早点看到。

如果你绑定到ViewModel上的实际枚举属性,而不是枚举的int表示,事情就变得棘手了。我发现有必要绑定到字符串表示,而不是在上述所有示例中预期的int值。

您可以通过将一个简单的文本框绑定到ViewModel上想要绑定的属性来判断是否存在这种情况。如果显示文本,则绑定到字符串。如果它显示一个数字,则绑定到该值。注意,我已经使用了两次显示,这通常是一个错误,但这是它工作的唯一方式。

<ComboBox SelectedValue="{Binding ElementMap.EdiDataType, Mode=TwoWay}"
                      DisplayMemberPath="Display"
                      SelectedValuePath="Display"
                      ItemsSource="{Binding Source={core:EnumToItemsSource {x:Type edi:EdiDataType}}}" />

Greg