简体   繁体   English

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

[英]How do I bind an enum to a ComboBox and hide a certain value in C#

I have an enum in the form of:我有一个枚举形式:

public enum BlueOrRed { None, Blue, Red}

Currently I am binding that to a ComboBox in Code because the binding is dependent on a selection in another ComboBox:目前我将其绑定到代码中的 ComboBox,因为绑定取决于另一个 ComboBox 中的选择:

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

I need the option, that BlueOrRed could also be None in the code behind.我需要这个选项,BlueOrRed 在后面的代码中也可以是 None 。 But I don't want to display that option in the ComboBox.但我不想在 ComboBox 中显示该选项。

I am aware of a similar Question , but that answer unfortunately doesn't really aplly to my problem.我知道一个类似的问题,但不幸的是,这个答案并不真正适用于我的问题。

The GetValues method will return all of these constants as an array. GetValues方法将所有这些常量作为数组返回。 Instead create a custom list.而是创建一个自定义列表。

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

If you do not want to create the list yourself, you can also exclude the None constant using Linq.如果您不想自己创建列表,也可以使用 Linq 排除None常量。

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

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

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