// Copyright (c) 2024- schick Informatik // Description: Helpers to display localized Enum values in Comboboxes // https://stackoverflow.com/questions/29658721/enum-in-wpf-comboxbox-with-localized-names // using System; using System.Globalization; using System.Windows.Data; using System.Windows.Markup; namespace BreCalClient { #region class EnumToStringConverter public sealed class EnumToStringConverter : IValueConverter { public object? Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) { return null; } return Resources.Resources.ResourceManager.GetString(value.ToString() ?? ""); } public object? ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { string str = (string)value; foreach (object enumValue in Enum.GetValues(targetType)) { if (str == Resources.Resources.ResourceManager.GetString(enumValue.ToString() ?? "")) { return enumValue; } } return null; } } #endregion #region class EnumerateExtension public sealed class EnumerateExtension : MarkupExtension { public Type Type { get; set; } public EnumerateExtension(Type type) { this.Type = type; } public override object ProvideValue(IServiceProvider serviceProvider) { string[] names = Enum.GetNames(Type); // skip value "0" == "Unknown" (we dont want this selectable in the Combobox) // NOTE: This will only work in the future if the first element is always "undefined" aka unused string[] values = new string[names.Length - 1]; for (int i = 0; i < names.Length - 1; i++) { values[i] = Resources.Resources.ResourceManager.GetString(names[i + 1]) ?? names[i]; } return values; } } #endregion }