mirror of
https://github.com/Artemis-RGB/Artemis
synced 2025-12-13 05:48:35 +00:00
48 lines
1.7 KiB
C#
48 lines
1.7 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.ComponentModel;
|
|
using System.Globalization;
|
|
using System.Linq;
|
|
using System.Windows.Data;
|
|
using System.Windows.Markup;
|
|
|
|
namespace Artemis.UI.Converters
|
|
{
|
|
[ValueConversion(typeof(Enum), typeof(IEnumerable<Tuple<object, object>>))]
|
|
public class EnumToCollectionConverter : MarkupExtension, IValueConverter
|
|
{
|
|
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
|
{
|
|
return GetAllValuesAndDescriptions(value.GetType());
|
|
}
|
|
|
|
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
public override object ProvideValue(IServiceProvider serviceProvider)
|
|
{
|
|
return this;
|
|
}
|
|
|
|
private static string Description(Enum value)
|
|
{
|
|
var attributes = value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
|
|
if (attributes.Any())
|
|
return (attributes.First() as DescriptionAttribute)?.Description;
|
|
|
|
// If no description is found, the least we can do is replace underscores with spaces
|
|
var ti = CultureInfo.CurrentCulture.TextInfo;
|
|
return ti.ToTitleCase(ti.ToLower(value.ToString().Replace("_", " ")));
|
|
}
|
|
|
|
private static IEnumerable<Tuple<object, object>> GetAllValuesAndDescriptions(Type t)
|
|
{
|
|
if (!t.IsEnum)
|
|
throw new ArgumentException($"{nameof(t)} must be an enum type");
|
|
|
|
return Enum.GetValues(t).Cast<Enum>().Select(e => new Tuple<object, object>(e, Description(e))).ToList();
|
|
}
|
|
}
|
|
} |