Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Is there a better way to data bind enums in wpf?


Asked by Edgar Lawrence on Dec 03, 2021 FAQ



Now that we have our enum binding working perfectly without the need for that silly ObjectDataProvider, we can improve our enum experience. It is very common to have a enum to represent the values, while at the same time, give the enum value a description so that it is more readable to your user.
Furthermore,
Normally if you were going to data bind a control to your enum you would need to go through a number of steps. First you need to add a XAML namespace for your local enum type and to System in MSCorLib. Then you would to create an ObjectDataProvider as a resource.
Also Know, Create a static class called “EnumClass” containing an Enum called “Positions” as mentioned below. Now prepare a WPF window with one combobox as shown below. Now move to App.xaml file to declare ObjectDataProvider to prepare an object in xaml to use as binding source for combobox. First Add following namespace to App.xaml page.
Keeping this in consideration,
Unfortunately there isn't a direct way to use an enumeration as a data binding source. However, the Enum.GetValues (Type) method returns a collection of values. These values can be wrapped in an ObjectDataProvider and used as a data source.
In addition,
It is very common to have a enum to represent the values, while at the same time, give the enum value a description so that it is more readable to your user. For example; let’s say you have an enum will all the state abbreviations (ID, TX, AZ, etc.), but you would much rather display the full state name (Texas, Idaho, Arizona, etc.).