Hello Devz,
In a previous post I was talking about the fact that there is no “out-of-the-box” solution to bind an Enum to a ComboBox. And I described the WPF way of doing it with the ObjectDataProvider defined in the XAML.
Here is another way, more code oriented than XAML.
This is the XAML part:
<ComboBox HorizontalAlignment="Center" VerticalAlignment="Center" MinWidth="150" ItemsSource="{Binding Source={local:EnumBindingSource {x:Type local:StatusEnum}}}"/>
Here is our Enum:
public enum StatusEnum { None = 0, Waiting = 1, Running = 2, Success = 3, Warning = 4, Error = 5 }
And here is our MarkupExtension:
using System; using System.Windows.Markup; namespace EnumBindingMarkupExtension { public class EnumBindingSourceExtension : MarkupExtension { private Type _enumType; public Type EnumType { get { return this._enumType; } set { if (value != this._enumType) { if (null != value) { Type enumType = Nullable.GetUnderlyingType(value) ?? value; if (!enumType.IsEnum) throw new ArgumentException("Type must be an Enum."); } this._enumType = value; } } } public EnumBindingSourceExtension() { } public EnumBindingSourceExtension(Type enumType) { this.EnumType = enumType; } public override object ProvideValue(IServiceProvider serviceProvider) { if (null == this._enumType) throw new InvalidOperationException("The EnumType must be specified."); Type actualEnumType = Nullable.GetUnderlyingType(this._enumType) ?? this._enumType; Array enumValues = Enum.GetValues(actualEnumType); if (actualEnumType == this._enumType) return enumValues; Array tempArray = Array.CreateInstance(actualEnumType, enumValues.Length + 1); enumValues.CopyTo(tempArray, 1); return tempArray; } } }
If you want to go further, please have a look to the best way to bind your Enum to a ComboBox with the Description Attribute in your MVVM WPF application.
Happy binding! 😉
[…] my two previous posts, I was talking about how to bind an enum (the classic way and the other way). But these two have two major issues. First the all the items from the Enum will be binded. And […]