In this video, I answer the question “How to Bind an Enum to a ComboBox in WPF?”.
When most WPF developers bind an enum to a combobox in WPF, they use the standard ObjectDataProvider approach. This consists of creating an ObjectDataProvider as a resource in tour wpf application. Setting the MethodName and ObjectType properties. Then you have to provide the ObjectDtaProvider MethodParameters which is the type of the enum you want to bind. Finally, you can then bind your ComboBox ItemsSource property to the ObjectDataProvider resources, which will essentially bind your enum to the combobox.
That’s a lot of code, and it sucks really bad. After seeing the “official” (crappy) WPF approach to bind an enum to a ComboBox using an ObjectDataProvider, I will show you my approach.
My approach takes advantage of a custom MarkupExtension that can be used to bind an enum to a ComboBox just by setting the binding on the ItemsSource property. No need for an ObjectDataprovider.
You’ll soon see why my way is the better approach to bind an enum to a combobox in WPF.
I’ve been using this approach for years!
Actually, you can make it even simpler: you don’t need the binding at all! And you also don’t need x:Type, since the constructor argument is of type Type.
ItemsSource=”{local:EnumBindingSource local:Status}”
Yes, I noticed that after recording the video. Sometimes when I am recording, coding, and talking I forget some stuff. If you look at the pinned comment on that video, I point that out.
Good video!
It reminds me a blog post I wrote 6 years ago (time flies…): https://www.meziantou.net/how-to-bind-an-enum-to-a-combobox-in-wpf.htm
In my post I support localizing enum values using the Display attribute. I also publish a NuGet package (Meziantou.Framework.WPF) which contains the markup extensions.
Very similar approach indeed. Thanks for sharing.