【问题标题】:How do I bind an enum to a ComboBox and hide a certain value in C#如何将枚举绑定到 ComboBox 并在 C# 中隐藏某个值
【发布时间】:2020-07-24 08:27:05
【问题描述】:

我有一个枚举形式:

public enum BlueOrRed { None, Blue, Red}

目前我将其绑定到代码中的组合框,因为绑定依赖于另一个组合框中的选择:

if (OtherComboBox.SelectedItem == Color.BlueOrRed)
{
    ThisComboBOx.ItemsSource = Enum.GetValues(typeof(BlueOrRed));
}
else ...

我需要选项,BlueOrRed 在后面的代码中也可以是 None。但我不想在 ComboBox 中显示该选项。

我知道有一个类似的Question,但不幸的是,这个答案并不真正适用于我的问题。

【问题讨论】:

  • ItemsSource = new BlueOrRed[] { BlueOrRed.Blue, BlueOrRed.Red };
  • 可能是answer。但我没有测试过。

标签: c# wpf data-binding enums


【解决方案1】:

GetValues 方法会将这些常量的所有作为数组返回。而是创建一个自定义列表。

ThisComboBOx.ItemsSource = new List<BlueOrRed> {BlueOrRed.Blue, BlueOrRed.Red};

如果您不想自己创建列表,也可以使用 Linq 排除 None 常量。

ThisComboBOx.ItemsSource = ((BlueOrRed[]) Enum.GetValues(typeof(BlueOrRed))).Except(new[] { BlueOrRed.None });

【讨论】:

    猜你喜欢
    • 2014-01-26
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    • 2011-07-03
    • 1970-01-01
    • 2016-09-15
    • 2016-12-12
    • 2010-11-16
    相关资源
    最近更新 更多