简体   繁体   中英

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:

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. But I don't want to display that option in the 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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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