如何在DataGridTextColumn中显示枚举类型?

时间:2011-11-21 05:20:49

标签: wpf enums wpfdatagrid

我已经列出并且我将这些列表绑定到工作正常的数据网格,但在该规则类中我有一个枚举类型,这是“类型”所以在数据网格中我得到的类型列为空,那怎么能我在datagrid列中得到枚举类型,PLZ帮帮我。

谢谢, @nagaraju。

2 个答案:

答案 0 :(得分:3)

通常它应该通过绑定直接转换为它的String repersentation ...但如果不是你可以写一个值转换器

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

您可以按如下方式使用转换器

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

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

我认为你错过了....你需要制作一个具有该名称的静态资源

答案 1 :(得分:2)

声明类如:

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();
    }
}

在xaml中使用转换器作为..

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

像...一样绑定。

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

这对我有用..

@nagaraju。