【问题标题】:How can I populate a WPF combo box in XAML with all the items from a given enum?如何使用给定枚举中的所有项目填充 XAML 中的 WPF 组合框?
【发布时间】:2010-10-06 23:42:55
【问题描述】:

假设我有一个包含四个值的枚举:

public enum CompassHeading
{
    North,
    South,
    East,
    West
}

使用这些项目填充 ComboBox 需要什么 XAML?

<ComboBox ItemsSource="{Binding WhatGoesHere???}" />

理想情况下,我不必为此设置 C# 代码。

【问题讨论】:

  • 我刚刚阅读了 Eric Burke 最近发表的关于执行此操作的 Swing JComboBox 类的帖子,并想“嘿,我发誓我看到了一个关于这个的 SO 问题......”我很接近,但你想要 WPF ,而不是 Java/Swing。无论如何,这是为了后代:stuffthathappens.com/blog/2009/02/10/…

标签: .net wpf data-binding combobox enums


【解决方案1】:

这可能就像在教堂里发誓,但我想在 XAML 中显式声明每个 ComboBoxItem,原因如下:

  • 如果我需要本地化,我可以将 XAML 提供给翻译人员并为自己保留代码。
  • 如果我有不适合给定 ComboBox 的枚举值,我不必显示它们。
  • 枚举的顺序在 XAML 中确定,不一定在代码中。
  • 可供选择的枚举值的数量通常不是很高。我会认为具有数百个值的枚举是代码异味。
  • 如果我需要在某些 ComboBoxItems 上使用图形或其他装饰,最简单的方法是把它放在它所属的 XAML 中,而不是一些棘手的模板/触发器的东西。
  • 保持简单,愚蠢

C# 示例代码:

    public enum number { one, two, three };

public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
    }

    private number _number = number.one;
    public number Number
    {
        get { return _number; }
        set {
            if (_number == value)
                return;
            _number = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("Number"));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

XAML 代码:

<Window x:Class="WpfApplication6.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="480" Width="677">
<Grid>
    <ComboBox SelectedValue="{Binding Number}" SelectedValuePath="Tag">
        <ComboBoxItem Content="En" Tag="One"/>
        <ComboBoxItem Content="To" Tag="Two"/>
        <ComboBoxItem Content="Tre" Tag="Three"/>
    </ComboBox>
</Grid>

如您所见,XAML 已本地化为挪威语,无需更改 C# 代码。

【讨论】:

  • 而且您可以获得开箱即用的设计时支持
【解决方案2】:

第三种解决方案:

这需要更多的前期工作,如果您绑定到大量枚举,从长远来看会更容易。使用以枚举类型为参数的转换器,并将其转换为字符串数组作为输出。

在 VB.NET 中:

Public Class EnumToNamesConverter
    Implements IValueConverter

    Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
        Return [Enum].GetNames(DirectCast(value, Type))
    End Function

    Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Throw New NotImplementedException()
    End Function
End Class

或者在 C# 中:

public sealed class EnumToNamesConverter : IValueConverter
{
  object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    return Enum.GetNames(value.GetType());
  }

  object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
    throw New NotSupportedException()
  }
}

然后在你的Application.xaml 中,添加一个全局资源来访问这个转换器:

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

最后在需要任何 Enum 值的任何 XAML 页面中使用转换器...

<ComboBox ItemsSource="{Binding
                        Source={x:Type local:CompassHeading},
                        Converter={StaticResource EnumToNamesConverter}}" />

【讨论】:

  • 嗨 maranite2,我喜欢这个解决方案的外观,但我无法让它与 TwoWay 绑定一起工作。绑定从控件到数据(当我保存时)有效,但它不适用于从数据到控件(组合框最初是空白的,应该选择一个值)。
【解决方案3】:

我认为使用 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);
    }
}

【讨论】:

  • 我想出了一个与你的课程几乎完全一样的课程,但没有看到你的课程。我在 return 语句之前添加了一个检查:enumType.IsEnum。
【解决方案4】:

您可以使用 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

【讨论】:

  • 谢谢,这个解决方案似乎也适用于 TwoWay 绑定。请注意,IsSynchronizedWithCurrentItem="true" 是这个问题的红鲱鱼(您可能希望将其删除以清楚其他访问者)。
  • 这不支持本地化。
  • @Guge:不,它不支持,但枚举也不支持本地化。您必须为每个位置创建不同的枚举,或者您必须附加一个可以为您生成本地化值的属性(它将使用某种键控查找),在这种情况下,问题和答案不要'不再适用。
  • @casperOne:没错!我不认为枚举是用户界面的一部分,而只是一种清理整数在代码中用于符号使用的方法。以这种方式使枚举对用户可见是层分离不佳的味道。
  • @Guge:也许吧,但对于提出这个问题的人来说,这更像是一个问题,不是吗?这个问题很具体,我回答的时候并不关心背后的原因。
【解决方案5】:

有关替代技术和衍生技术的分步演练,请尝试以下网页:

The Missing .NET #7: Displaying Enums in WPF

本文还演示了一种覆盖某些值的表示的方法。包含大量代码示例的好书。

【讨论】:

    【解决方案6】:

    Here 是 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}}" />
    

    还可以查看: Databinding an enum property to a ComboBox in WPF

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-03
      • 1970-01-01
      • 2015-06-28
      • 1970-01-01
      • 1970-01-01
      • 2014-08-08
      相关资源
      最近更新 更多