如何将枚举绑定到ComboBox并在C#中隐藏某个值



我有一个形式为:的枚举

public enum BlueOrRed { None, Blue, Red}

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

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

我需要一个选项,BlueOrRed也可以在后面的代码中为None。但我不想在组合框中显示该选项。

我知道一个类似的问题,但不幸的是,这个答案并不能真正解决我的问题。

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

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

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

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

最新更新