Enum Description Converter #3136
Replies: 6 comments
-
|
This would be a good addition. |
Beta Was this translation helpful? Give feedback.
-
|
yeah this would be great! |
Beta Was this translation helpful? Give feedback.
-
|
I like this idea... it will make things more fluid and able to interconnect. |
Beta Was this translation helpful? Give feedback.
-
|
I would rely on this a lot.. a good idea and good addition! |
Beta Was this translation helpful? Give feedback.
-
|
For those who may not be aware, CommunityToolkit.Maui.Markup provides both FuncConverter and BindableObject extensions, allowing you to focus on supplying delegates while the CommunityToolkit handles the converter boilerplate. This becomes especially useful when generalizing the pattern to support localized strings. FuncConverter examplepublic static class EnumConverters
{
public static string ModeNameToString(ModeName mode) => mode switch
{
ModeName.LightMode => "Light Mode",
ModeName.DarkMode => "Dark Mode",
ModeName.System => "System",
_ => throw new ArgumentOutOfRangeException(nameof(mode), mode, null)
};
public static FuncConverter<ModeName, string> ModeNameConverter = new(ModeNameToString);
}BindableObject extension examplevisualElement.Bind(Button.TextProperty, static (MainPage p) => p.SelectedModeName, convert: EnumConverters.ModeNameToString); |
Beta Was this translation helpful? Give feedback.
-
|
Great addition! This will be a great support for developers! |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
This converter converts Enum values into readable text so they display nicely in the UI. When an Enum value is passed in, the converter looks for attributes that provide a more user-friendly name. If one is found, it uses that value; otherwise it simply uses the Enum’s name. This ensures that Enum values can be displayed clearly while still working correctly even when no attributes are defined. Unit tests are included to verify the expected behavior.
Technically, the converter uses reflection to inspect the Enum member’s metadata at runtime. It first checks for a DisplayAttribute and returns its Name property when present. If that attribute is not found or does not contain a value, it falls back to DescriptionAttribute and returns its Description. If neither attribute is applied, the converter returns the Enum member’s default string value. The implementation also guards against null inputs and is designed as a one-way converter, with unit tests validating attribute precedence, whitespace handling, and fallback behavior.
Beta Was this translation helpful? Give feedback.
All reactions