使用枚举中的值填充组合框

时间:2015-01-01 15:50:22

标签: c# wpf xaml data-binding

我有这样的 enum

enum Beep {A, B, C }

现在,我希望使用以下这些值填充我的组合框(想法是遵循other's example)。

<ComboBox x:Name="comboBox1" 
          ...
          ItemsSource="Binding Source={StaticResource Beep}" />

然而,绑定变得有点过于静态,并且字面上给出了我正在输入的确切字符串。我做错了什么以及如何解决它?

enter image description here

我也试过按照提示添加这样的东西。但是无济于事。

public List<Beep> Beepies
{
  get
  {
    return new List<Beep>{ Beep.A }
  }
}

还有什么可以做的呢?如果我在下面的代码中绑定,我可以将值放入框中。但这不是重点 - 我希望XAMLize这种方法。

comboBox1.ItemsSource = Enum.GetValues(typeof(Beep));

1 个答案:

答案 0 :(得分:0)

您必须使用集合进行绑定。尝试创建List<Beep>

创建一个枚举enum

的转换器
public class EnumConverter : IValueConverter
{
  public object Convert(object value, ...)
  {
    return Enum.GetValues(value.GetType());
  }
}

然后,您可以在绑定XAMLise方法时使用此转换器:

<!-- Put this in resources somewhere -->
<Converters:EnumConverter x:Key="MyEnumConverter"/>

<!-- Change your binding to include the new converter -->
<ComboBox x:Name="comboBox1" 
          ...
          ItemsSource="Binding Source={StaticResource Beep}, 
                       Converter={StaticResource MyEnumConverter}" />