繁体   English   中英

如何将枚举绑定到 WPF 中的 combobox 控件?

[英]How to bind an enum to a combobox control in WPF?

我试图找到一个简单的示例,其中枚举按原样显示。 我见过的所有示例都试图添加漂亮的显示字符串,但我不想要那种复杂性。

基本上我有一个 class 包含我绑定的所有属性,首先将 DataContext 设置为此 class,然后在 xaml 文件中指定这样的绑定:

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

但这并没有将ComboBox中的枚举值显示为项目。

您可以通过将以下代码放入 Window Loaded的事件处理程序中来从代码中执行此操作,例如:

yourComboBox.ItemsSource = Enum.GetValues(typeof(EffectStyle)).Cast<EffectStyle>();

如果您需要在 XAML 中绑定它,您需要使用ObjectDataProvider创建 object 作为绑定源:

<Window x:Class="YourNamespace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:System="clr-namespace:System;assembly=mscorlib"
        xmlns:StyleAlias="clr-namespace:Motion.VideoEffects">
    <Window.Resources>
        <ObjectDataProvider x:Key="dataFromEnum" MethodName="GetValues"
                            ObjectType="{x:Type System:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="StyleAlias:EffectStyle"/>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>
    <Grid>
        <ComboBox ItemsSource="{Binding Source={StaticResource dataFromEnum}}"
                  SelectedItem="{Binding Path=CurrentEffectStyle}" />
    </Grid>
</Window>

请注意下一个代码:

xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:StyleAlias="clr-namespace:Motion.VideoEffects"

指导如何 map 命名空间和程序集,您可以在MSDN上阅读。

我喜欢在我的ViewModel中定义我要绑定的所有对象,因此我尽量避免在 xaml 中使用<ObjectDataProvider>

我的解决方案不使用视图中定义的数据,也不使用代码隐藏。 只有一个 DataBinding、一个可重用的 ValueConverter、一个获取任何 Enum 类型的描述集合的方法,以及 ViewModel 中要绑定的单个属性。

当我想将Enum绑定到ComboBox时,我要显示的文本永远不会与Enum的值匹配,因此我使用[Description()]属性为其提供我真正想在ComboBox中看到的文本。 如果我有一周中的几天的枚举,它看起来像这样:

public enum DayOfWeek
{
  // add an optional blank value for default/no selection
  [Description("")]
  NOT_SET = 0,
  [Description("Sunday")]
  SUNDAY,
  [Description("Monday")]
  MONDAY,
  ...
}

首先,我使用几种处理枚举的方法创建了助手 class。 一种方法获取特定值的描述,另一种方法获取类型的所有值及其描述。

public static class EnumHelper
{
  public static string Description(this Enum value)
  {
    var attributes = value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
    if (attributes.Any())
      return (attributes.First() as DescriptionAttribute).Description;

    // If no description is found, the least we can do is replace underscores with spaces
    // You can add your own custom default formatting logic here
    TextInfo ti = CultureInfo.CurrentCulture.TextInfo;
    return ti.ToTitleCase(ti.ToLower(value.ToString().Replace("_", " ")));
  }

  public static IEnumerable<ValueDescription> GetAllValuesAndDescriptions(Type t)
  {
    if (!t.IsEnum)
      throw new ArgumentException($"{nameof(t)} must be an enum type");

    return Enum.GetValues(t).Cast<Enum>().Select((e) => new ValueDescription() { Value = e, Description = e.Description() }).ToList();
  }
}

接下来,我们创建一个ValueConverter MarkupExtension继承使它更容易在 XAML 中使用,因此我们不必将其声明为资源。

[ValueConversion(typeof(Enum), typeof(IEnumerable<ValueDescription>))]
public class EnumToCollectionConverter : MarkupExtension, IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    return EnumHelper.GetAllValuesAndDescriptions(value.GetType());
  }
  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
    return null;
  }
  public override object ProvideValue(IServiceProvider serviceProvider)
  {
    return this;
  }
}

我的ViewModel只需要我的View可以为 combobox 的SelectedValueItemsSource绑定的 1 个属性:

private DayOfWeek dayOfWeek;

public DayOfWeek SelectedDay
{
  get { return dayOfWeek; }
  set
  {
    if (dayOfWeek != value)
    {
      dayOfWeek = value;
      OnPropertyChanged(nameof(SelectedDay));
    }
  }
}

最后绑定ComboBox视图(使用ItemsSource绑定中的ValueConverter )...

<ComboBox ItemsSource="{Binding Path=SelectedDay, Converter={x:EnumToCollectionConverter}, Mode=OneTime}"
          SelectedValuePath="Value"
          DisplayMemberPath="Description"
          SelectedValue="{Binding Path=SelectedDay}" />

要实施此解决方案,您只需复制我的EnumHelper class 和EnumToCollectionConverter class。 他们将与任何枚举一起使用。 另外,我没有在此处包含它,但ValueDescription class 只是一个简单的 class 具有 2 个公共 object 属性,一个称为Value ,一个称为Description 您可以自己创建,也可以更改代码以使用Tuple<object, object>KeyValuePair<object, object>

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

  1. 我制作了 class ,它提供了物品来源:

     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() }); } }
  2. 差不多就这些了……现在在XAML中使用它:

     <ComboBox DisplayMemberPath="DisplayName" ItemsSource="{persons:EnumToItemsSource {x:Type enums:States}}" SelectedValue="{Binding Path=WhereEverYouWant}" SelectedValuePath="Value" />
  3. 将“枚举:状态”更改为您的枚举

使用 ObjectDataProvider:

<ObjectDataProvider x:Key="enumValues"
   MethodName="GetValues" ObjectType="{x:Type System:Enum}">
      <ObjectDataProvider.MethodParameters>
           <x:Type TypeName="local:ExampleEnum"/>
      </ObjectDataProvider.MethodParameters>
 </ObjectDataProvider>

然后绑定到 static 资源:

ItemsSource="{Binding Source={StaticResource enumValues}}"

根据这篇文章

尼克的回答确实帮助了我,但我意识到它可以稍微调整一下,以避免额外的 class,ValueDescription。 我记得框架中已经存在一个 KeyValuePair class,所以可以使用它来代替。

代码仅略有变化:

public static IEnumerable<KeyValuePair<string, string>> GetAllValuesAndDescriptions<TEnum>() where TEnum : struct, IConvertible, IComparable, IFormattable
    {
        if (!typeof(TEnum).IsEnum)
        {
            throw new ArgumentException("TEnum must be an Enumeration type");
        }

        return from e in Enum.GetValues(typeof(TEnum)).Cast<Enum>()
               select new KeyValuePair<string, string>(e.ToString(),  e.Description());
    }


public IEnumerable<KeyValuePair<string, string>> PlayerClassList
{
   get
   {
       return EnumHelper.GetAllValuesAndDescriptions<PlayerClass>();
   }
}

最后是 XAML:

<ComboBox ItemSource="{Binding Path=PlayerClassList}"
          DisplayMemberPath="Value"
          SelectedValuePath="Key"
          SelectedValue="{Binding Path=SelectedClass}" />

我希望这对其他人有帮助。

您需要在枚举中创建一个值数组,该数组可以通过调用System.Enum.GetValues()来创建,并将您想要的项目的枚举Type传递给它。

如果为ItemsSource属性指定此项,则应使用枚举的所有值填充它。 您可能希望将SelectedItem绑定到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();
    }

和主要的 class (注意我使用 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,但会使帖子更长。

这个问题有很多很好的答案,我谦虚地提交我的。 我发现我的更简单,更优雅。 它只需要一个值转换器。

给定一个枚举...

public enum ImageFormat
{
    [Description("Windows Bitmap")]
    BMP,
    [Description("Graphics Interchange Format")]
    GIF,
    [Description("Joint Photographic Experts Group Format")]
    JPG,
    [Description("Portable Network Graphics Format")]
    PNG,
    [Description("Tagged Image Format")]
    TIFF,
    [Description("Windows Media Photo Format")]
    WDP
}

和一个价值转换器......

public class ImageFormatValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is ImageFormat format)
        {
            return GetString(format);
        }

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is string s)
        {
            return Enum.Parse(typeof(ImageFormat), s.Substring(0, s.IndexOf(':')));
        }
        return null;
    }

    public string[] Strings => GetStrings();

    public static string GetString(ImageFormat format)
    {
        return format.ToString() + ": " + GetDescription(format);
    }

    public static string GetDescription(ImageFormat format)
    {
        return format.GetType().GetMember(format.ToString())[0].GetCustomAttribute<DescriptionAttribute>().Description;

    }
    public static string[] GetStrings()
    {
        List<string> list = new List<string>();
        foreach (ImageFormat format in Enum.GetValues(typeof(ImageFormat)))
        {
            list.Add(GetString(format));
        }

        return list.ToArray();
    }
}

资源...

    <local:ImageFormatValueConverter x:Key="ImageFormatValueConverter"/>

XAML 声明...

    <ComboBox Grid.Row="9" ItemsSource="{Binding Source={StaticResource ImageFormatValueConverter}, Path=Strings}"
              SelectedItem="{Binding Format, Converter={StaticResource ImageFormatValueConverter}}"/>

查看 model...

    private ImageFormat _imageFormat = ImageFormat.JPG;
    public ImageFormat Format
    {
        get => _imageFormat;
        set
        {
            if (_imageFormat != value)
            {
                _imageFormat = value;
                OnPropertyChanged();
            }
        }
    }

结果 combobox...

绑定到枚举的组合框

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

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

只是为了好玩,我制作了一个小模板 class 来帮助解决这个问题,并将其发布到MSDN 示例页面 额外的位让我可以选择覆盖枚举的名称并让我隐藏一些枚举。 我的代码看起来很像尼克的(上图),我希望我早点看到。

运行样本;它包括对枚举的多个双向绑定

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

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

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

格雷格

public class EnumItemsConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (!value.GetType().IsEnum)
            return false;

        var enumName = value.GetType();
        var obj = Enum.Parse(enumName, value.ToString());

        return System.Convert.ToInt32(obj);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return Enum.ToObject(targetType, System.Convert.ToInt32(value));
    }
}

如果您直接绑定到枚举 object model 属性,您应该使用这种枚举值转换器扩展 Rogers 和 Greg 的答案。

我喜欢tom.maruska 的回答,但我需要支持我的模板在运行时可能遇到的任何枚举类型。 为此,我必须使用绑定来指定标记扩展的类型。 我能够在 nicolay.anykienko 的这个答案中工作,以提出一个非常灵活的标记扩展,在我能想到的任何情况下都可以使用。 它是这样消耗的:

<ComboBox SelectedValue="{Binding MyEnumProperty}" 
          SelectedValuePath="Value"
          ItemsSource="{local:EnumToObjectArray SourceEnum={Binding MyEnumProperty}}" 
          DisplayMemberPath="DisplayName" />

上面引用的混搭标记扩展的来源:

class EnumToObjectArray : MarkupExtension
{
    public BindingBase SourceEnum { get; set; }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        IProvideValueTarget target = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
        DependencyObject targetObject;
        DependencyProperty targetProperty;

        if (target != null && target.TargetObject is DependencyObject && target.TargetProperty is DependencyProperty)
        {
            targetObject = (DependencyObject)target.TargetObject;
            targetProperty = (DependencyProperty)target.TargetProperty;
        }
        else
        {
            return this;
        }

        BindingOperations.SetBinding(targetObject, EnumToObjectArray.SourceEnumBindingSinkProperty, SourceEnum);

        var type = targetObject.GetValue(SourceEnumBindingSinkProperty).GetType();

        if (type.BaseType != typeof(System.Enum)) return this;

        return Enum.GetValues(type)
            .Cast<Enum>()
            .Select(e => new { Value=e, Name = e.ToString(), DisplayName = Description(e) });
    }

    private static DependencyProperty SourceEnumBindingSinkProperty = DependencyProperty.RegisterAttached("SourceEnumBindingSink", typeof(Enum)
                       , typeof(EnumToObjectArray), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Inherits));

    /// <summary>
    /// Extension method which returns the string specified in the Description attribute, if any.  Oherwise, name is returned.
    /// </summary>
    /// <param name="value">The enum value.</param>
    /// <returns></returns>
    public static string Description(Enum value)
    {
        var attrs = value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
        if (attrs.Any())
            return (attrs.First() as DescriptionAttribute).Description;

        //Fallback
        return value.ToString().Replace("_", " ");
    }
}

简单明了的解释: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>

它工作得非常好和简单。
xaml

<ComboBox ItemsSource="{Binding MyEnumArray}">

。CS

public Array MyEnumArray
{
  get { return Enum.GetValues(typeof(MyEnum)); }
}

我正在添加我的评论(遗憾的是,在 VB 中,但这个概念可以很容易地在心跳中复制到 C#),因为我只需要参考这个并且不喜欢任何答案,因为它们太复杂了。 它不应该这么困难。

所以我想出了一个更简单的方法。 将枚举器绑定到字典。 将该字典绑定到 Combobox。

我的 combobox:

<ComboBox x:Name="cmbRole" VerticalAlignment="Stretch" IsEditable="False" Padding="2" 
    Margin="0" FontSize="11" HorizontalAlignment="Stretch" TabIndex="104" 
    SelectedValuePath="Key" DisplayMemberPath="Value" />

我的代码隐藏。 希望这可以帮助其他人。

Dim tDict As New Dictionary(Of Integer, String)
Dim types = [Enum].GetValues(GetType(Helper.Enumerators.AllowedType))
For Each x As Helper.Enumerators.AllowedType In types
    Dim z = x.ToString()
    Dim y = CInt(x)
    tDict.Add(y, z)
Next

cmbRole.ClearValue(ItemsControl.ItemsSourceProperty)
cmbRole.ItemsSource = tDict

使用ReactiveUI ,我创建了以下替代解决方案。 这不是一个优雅的一体化解决方案,但我认为至少它是可读的。

在我的情况下,将enum列表绑定到控件是一种罕见的情况,因此我不需要在代码库中扩展解决方案。 但是,可以通过将EffectStyleLookup.Item更改为Object来使代码更通用。 我用我的代码测试了它,不需要其他修改。 这意味着一个助手 class 可以应用于任何enum列表。 虽然这会降低它的可读性 - ReactiveList<EnumLookupHelper>没有很好的影响。

使用以下帮助程序 class:

public class EffectStyleLookup
{
    public EffectStyle Item { get; set; }
    public string Display { get; set; }
}

在 ViewModel 中,转换枚举列表并将其作为属性公开:

public ViewModel : ReactiveObject
{
  private ReactiveList<EffectStyleLookup> _effectStyles;
  public ReactiveList<EffectStyleLookup> EffectStyles
  {
    get { return _effectStyles; }
    set { this.RaiseAndSetIfChanged(ref _effectStyles, value); }
  }

  // See below for more on this
  private EffectStyle _selectedEffectStyle;
  public EffectStyle SelectedEffectStyle
  {
    get { return _selectedEffectStyle; }
    set { this.RaiseAndSetIfChanged(ref _selectedEffectStyle, value); }
  }

  public ViewModel() 
  {
    // Convert a list of enums into a ReactiveList
    var list = (IList<EffectStyle>)Enum.GetValues(typeof(EffectStyle))
      .Select( x => new EffectStyleLookup() { 
        Item = x, 
        Display = x.ToString()
      });

    EffectStyles = new ReactiveList<EffectStyle>( list );
  }
}

ComboBox中,利用SelectedValuePath属性绑定到原始enum值:

<ComboBox Name="EffectStyle" DisplayMemberPath="Display" SelectedValuePath="Item" />

在视图中,这允许我们将原始enum绑定到 ViewModel 中的SelectedEffectStyle ,但在ComboBox中显示ToString()值:

this.WhenActivated( d =>
{
  d( this.OneWayBind(ViewModel, vm => vm.EffectStyles, v => v.EffectStyle.ItemsSource) );
  d( this.Bind(ViewModel, vm => vm.SelectedEffectStyle, v => v.EffectStyle.SelectedValue) );
});

尼克的解决方案可以进一步简化,没有什么花哨的,你只需要一个转换器:

[ValueConversion(typeof(Enum), typeof(IEnumerable<Enum>))]
public class EnumToCollectionConverter : MarkupExtension, IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var r = Enum.GetValues(value.GetType());
        return r;
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }
}

然后,您可以在希望组合框出现的任何地方使用它:

<ComboBox ItemsSource="{Binding PagePosition, Converter={converter:EnumToCollectionConverter}, Mode=OneTime}"  SelectedItem="{Binding PagePosition}" />

我不建议按原样实施,但希望这可以激发一个好的解决方案。

假设您的枚举是 Foo。 然后你可以做这样的事情。

public class FooViewModel : ViewModel
{
    private int _fooValue;

    public int FooValue
    {
        get => _fooValue;
        set
        {
            _fooValue = value;
            OnPropertyChange();
            OnPropertyChange(nameof(Foo));
            OnPropertyChange(nameof(FooName));
        }
    }
    public Foo Foo 
    { 
        get => (Foo)FooValue; 
        set 
        { 
            _fooValue = (int)value;
            OnPropertyChange();
            OnPropertyChange(nameof(FooValue));
            OnPropertyChange(nameof(FooName));
        } 
    }
    public string FooName { get => Enum.GetName(typeof(Foo), Foo); }

    public FooViewModel(Foo foo)
    {
        Foo = foo;
    }
}

然后在Window.Load方法上,您可以将所有枚举加载到ObservableCollection<FooViewModel>中,您可以将其设置为 combobox 的 DataContext。

我只是保持简单。 我在 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}">
<Window.Resources>
        <ObjectDataProvider x:Key="DiaryTypeEnum"
       MethodName="GetValues" ObjectType="{x:Type System:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="z:Enums+DiaryType"/>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
</Window.Resources>
...
<ComboBox ItemsSource="{Binding Source={StaticResource DiaryTypeEnum}}" SelectedItem="{x:Static z:Enums+DiaryType.Defect}" />

其中 z 它的 xmlns:z="clr-namespace:ProjName.Helpers"

我的枚举到 static class

  public static class Enums
    {
        public enum DiaryType
        {
            State,
            Defect,
            Service,
            Other
        }
        public enum OtherEnumOrMethods
        {
           //TODO
        }
    }

这是我的简短回答。

public enum Direction { Left, Right, Up, Down };
public class Program
{
    public Direction ScrollingDirection { get; set; }
    public List<string> Directions { get; } = new List<string>();

    public Program()
    {
        loadListDirection();
    }

    private void loadListDirection()
    {
        Directions.AddRange(Enum.GetNames(typeof(Direction)));
    }
}

和 Xaml:

<ComboBox SelectedIndex="0" ItemsSource="{Binding Path=Directions, Mode=OneWay}" SelectedItem="{Binding Path=ScrollingDirection, Mode=TwoWay}"/>

祝你好运!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM