How to Bind an Enum to a ComboBox in WPF

Опубликовано: 20 Октябрь 2024
на канале: Brian Lagunas
18,429
418

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 approch 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.

Be sure to watch my new Pluralsight course "Introduction to Prism for WPF":
https://pluralsight.pxf.io/bE3rB

Sponsor Me:
https://github.com/sponsors/brianlagunas

Follow Me:
Twitter:   / brianlagunas  
Twitch:   / brianlagunas  
Blog: http://brianlagunas.com
GitHub: https://github.com/brianlagunas