【发布时间】:2011-11-21 05:20:48
【问题描述】:
我有列表,我将这些列表绑定到工作正常的数据网格,但在那个规则类中,我有一个枚举类型,它是“类型”,所以在数据网格中,我将类型列设为空,所以怎么能我在数据网格列中得到枚举类型请帮助我。
谢谢, @nagaraju。
【问题讨论】:
标签: wpf enums wpfdatagrid
我有列表,我将这些列表绑定到工作正常的数据网格,但在那个规则类中,我有一个枚举类型,它是“类型”,所以在数据网格中,我将类型列设为空,所以怎么能我在数据网格列中得到枚举类型请帮助我。
谢谢, @nagaraju。
【问题讨论】:
标签: wpf enums wpfdatagrid
通常它应该通过绑定直接转换为它的字符串表示...但如果不是你可以编写一个值转换器
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>
我认为你错过了....你需要创建一个该名称的静态资源
【讨论】:
throw new NotImplementedException(); 而不是return null;。它是一种形式,将来会使调试更容易:)
声明类如:
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。
【讨论】: