System.Windows.Controls.EnumDisplayNameConverter.Convert C# (CSharp) Method

Convert() public method

Convertes the value parameter from an enumeration value to the localized name of the enumeration value.
public Convert ( object value, Type targetType, object parameter, CultureInfo culture ) : object
value object The value of an enum that is to be converted.
targetType Type The type to which the value is to be converted. In this case it is always string.
parameter object A paramter that is not used in this implementation.
culture System.Globalization.CultureInfo The culture information of the current culture, so that parsing can be adjusted to cultural conventions.
return object
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            // Checks if the value provided is null, if so then tells the converter that the value is unset
            if (value == null)
                return DependencyProperty.UnsetValue;

            // Checks if the enum type, from which is to be converted, defines the value that is to be converted to its localized name, if not, then tells the converter, that the value is unset
            if (!(value is Enum) || !Enum.IsDefined(value.GetType(), value))
                return DependencyProperty.UnsetValue;

            // Checks if the enumeration value has a display name attribute, if not then tells the converter that the value is unset, otherwise the localized display name is returned
            DisplayAttribute displayAttribute = value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DisplayAttribute), false).OfType<DisplayAttribute>().FirstOrDefault();
            if (displayAttribute == null)
                return DependencyProperty.UnsetValue;

            // Creates a new resource manager in order to get the localized display name for the enumeration value
            ResourceManager resourceManager = new ResourceManager(displayAttribute.ResourceType);

            // Retrieves the localized display name and returns it if it exists, if it does not exist, then just the resource name is returned
            string name = resourceManager.GetString(displayAttribute.Name);
            return name == null ? displayAttribute.Name : name;
        }
EnumDisplayNameConverter