Part 2. Displaying localized names of enum values in WPF application
To achieve the human readable enums I have performed following steps.
- For each language I want to support I have added a resource (.resx) file with key equals the string representation of the enum value.
- Then we decorate our enum values with Display attribute as follows
As a description we can provide a strict value that will be displayed or, when setting also RepositoryType, we provide the resource key which will be used to find localized description in a resources.
- Now, when every enum value has its display attribute it is easy to get its value using following extension method
- Then I have added custom TypeConverter to convert enum type to its localized name
and decorated enum values with this converter.
Custom type converter is a very useful approach that facilitates binding enum values in WPF applications without any conversion or additional operations.
Ok. It seems to be a mass of strange classes, but you will see later that they are quite useful. Anyway for each new enum type you just need to decorate this type with EnumToLocalizedName converter and LocalizedDescription attributes and everything works in WPF and as you will later see also in MVC 3 application.
If we now want to bind a list of our Client objects described in Part 1, exposed in ViewModel as an observable collection
to the view in DataGrid component, we just do following
and that’s it. We have localized values in column Status for each Client. Thanks to the type converter the displayed values are properly localized according to the current culture. If we now want to change the language to Polish then it is as simple as writing
and reloading bindable properties.
Additionally if we want to get the list of all possible values of particular Enum type we do it following way