How to display Enum type in DataGridTextColumn?

2020-05-06 17:26发布

问题:

I've List and i bind these list to datagrid that is working fine, but in that Rule class i've one enum type Which is "Type" so in the datagrid i'm getting Type column as empty so how can i get enum type in datagrid column plz help me.

Thanks, @nagaraju.

回答1:

Usually its should be converted to Its String repersentation directly by binding... but if not the you can write a Value Converter

public class EnumConverter : IValueConverter
{
    #region Implementation of IValueConverter
    /// <summary>
    /// Converts a value. 
    /// </summary>
    /// <returns>
    /// A converted value. If the method returns null, the valid null value is used.
    /// </returns>
    /// <param name="value">The value produced by the binding source.
    ///                 </param><param name="targetType">The type of the binding target property.
    ///                 </param><param name="parameter">The converter parameter to use.
    ///                 </param><param name="culture">The culture to use in the converter.
    ///                 </param>
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return ((MyEnum)value).ToString()        }
    /// <summary>
    /// Converts a value. 
    /// </summary>
    /// <returns>
    /// A converted value. If the method returns null, the valid null value is used.
    /// </returns>
    /// <param name="value">The value that is produced by the binding target.
    ///                 </param><param name="targetType">The type to convert to.
    ///                 </param><param name="parameter">The converter parameter to use.
    ///                 </param><param name="culture">The culture to use in the converter.
    ///                 </param>
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return  null;
    }
    #endregion
}
# endregion

You can use the the Converter as follows

<.... Binding="{Binding Path=MyObject,Converter="{StaticResource ResourceKey=enumConverter}}"

<Window.Resources>
    <local:EnumConverter x:Key="enumConverter"/>
</WindowResources>

I think thats you are missing.... you need to make a Static resource of that name



回答2:

Declare class like:

public class EnumConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return ((YourEnumType)value).ToString();
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

use converter in xaml as..

<Window.Resources>
    <local:EnumConverter x:Key="enumConverter"/>
</Window.Resources>

Binding like..

<... Binding="{Binding Path=Type,Converter={StaticResource enumConverter}}" .../>

Thats worked for me..

@nagaraju.