asquared
asquared

Reputation: 370

Change displayed text of WPF ComboBox containing an Enum?

Situation:

C# with WPF and .NET 4.5.

I have an Enum defined in an external library. Let´s say it´s called SomeEnum and contains items "SomeValue1", "SomeValue2, "SomeValue3", and many more.

I have a ComboBox filled with these values like this:

comboBoxValues.ItemsSource = Enum.GetValues(typeof(SomeEnum));

The ComboBox, as expected, shows:

SomeValue1

SomeValue2

SomeValue3

...

Question:

Can I somehow change only the displayed values so that the "Some" part is missing. So that the ComboBox only shows this:

Value1

Value2

Value3

...

But: The SelectedValue for "Value1" should still be "SomeValue1".

Upvotes: 0

Views: 268

Answers (1)

Krzysztof Skowronek
Krzysztof Skowronek

Reputation: 2936

You can use LINQ to just trim the strings:

comboBoxValues.ItemsSource = Enum.GetValues(typeof(SomeEnum)).Select(x => x.ToString().TrimStart("Value"));    

But to be honest I would suggest making a two way converter, so that then you can bind SelectedItem to SomeEnum SomeProperty {get;set;} or setting up a Dictionary like here

Upvotes: 2

Related Questions