using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Controls;
using Common.Helpers;
namespace MultiTerm.Wpf.ValueConverters;
///
/// Converts an Enum (using its Description Attribute) to a Menu Item.
/// The Menu Item has the Description assigned to its Header.
/// If the Enum has no Description, it will convert the Enum Value to string and use this.
///
[ValueConversion(typeof(Enum), typeof(MenuItem))]
public class EnumDescriptionToMenuItemConverter : IValueConverter
{
///
/// Convert from Data Source to Dependency Object type.
/// Here: Enum type to MenuItem.
///
/// value to convert
/// type to convert to
/// no parameter required
/// most likely CultureInfo.CurrentCulture
/// New MenuItem with Enum description in Header property
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Enum enumValue = (Enum)value;
string description = EnumHelpers.GetEnumDescription(enumValue);
MenuItem newMenuItem = new()
{
Header = description
};
return newMenuItem;
}
///
/// Convert from Dependency Object type to Data Source type.
/// Here: MenuItem to Enum type.
///
/// value to convert
/// type to convert to
/// no parameter required
/// most likely CultureInfo.CurrentCulture
/// Enum value of the MenuItem that was converted
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// guard argument null
if (targetType == null) { throw new ArgumentNullException(nameof(targetType)); }
if (value == null) { throw new ArgumentNullException(nameof(value)); }
// extract menu item and guard null
if (value is not MenuItem menuObject)
{
throw new Exception($"Cannot convert value that is not of type {nameof(MenuItem)} with {nameof(EnumDescriptionToMenuItemConverter)}");
}
// get all enum descriptions and iterate
var enumObj = EnumHelpers.CreateInstanceOfEnumType(targetType);
var descriptionToEnumValue = EnumHelpers.GetAllEnumDescriptions(enumObj);
foreach (var kvp in descriptionToEnumValue)
{
// compare key (enum description) to menu header
if(String.Compare(kvp.Key, menuObject.Header.ToString(), true) == 0)
{
// if correct description is found, return according enum value
return kvp.Value;
}
}
// if nothing worked => return value
return value;
}
}