Files
DP44/Common/DTS.Common.SharedResource/EnumDescriptionTypeConverterShared.cs
2026-04-17 14:55:32 -04:00

54 lines
2.5 KiB
C#

using DTS.Common.SharedResource.Strings;
using System;
using System.ComponentModel;
using System.Linq;
namespace DTS.Common.Converters
{
/// <summary>
/// Display enum description instead of enum value
/// http://brianlagunas.com/a-better-way-to-data-bind-enums-in-wpf/
/// </summary>
public class EnumDescriptionTypeConverterShared : EnumConverter
{
public EnumDescriptionTypeConverterShared(Type type)
: base(type)
{
}
/// <summary>
/// Modifies the source data before passing it to the target for display in the UI.
/// </summary>
/// <param name="value">The value to be converted</param>
/// <param name="context">The source data being passed to the target.</param>
/// <param name="culture">The culture of the conversion.</param>
/// <param name="destinationType">The System.Type of data expected by the target dependency property.</param>
/// <returns>The value to be passed to the target dependency property.</returns>
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType != typeof(string)) return base.ConvertTo(context, culture, value, destinationType);
if (value == null) return string.Empty;
var fi = value.GetType().GetField(value.ToString());
if (fi == null) return string.Empty;
var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (!attributes.Any() || string.IsNullOrEmpty(attributes[0].Description)) return value.ToString();
var s = StringResources.ResourceManager.GetString(attributes[0].Description);
return string.IsNullOrWhiteSpace(s) ? attributes[0].Description : s;
}
public static string GetEnumDescription(Enum value)
{
var fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes
(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
var s = StringResources.ResourceManager.GetString(attributes[0].Description);
if (!string.IsNullOrWhiteSpace(s)) { return s; }
return attributes[0].Description;
}
return value.ToString();
}
}
}