【发布时间】:2018-02-13 11:06:53
【问题描述】:
我有一个枚举描述转换器
public class EnumDescriptionConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
//// parameter need current item, but null or "Value"
if (Enum.IsDefined(value.GetType(), value) == false)
return System.Windows.DependencyProperty.UnsetValue;
string parameterString = Enum.GetName(value.GetType(), value);
if (parameterString == null)
return System.Windows.DependencyProperty.UnsetValue;
var desc = (value.GetType().GetField(parameterString).GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault() as DescriptionAttribute);
if (desc != null)
return desc.Description;
else
return parameter.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
我喜欢将当前组合框项作为 ConverterParameter 传递给转换器
<ComboBox Name="test" Grid.Column="1" Grid.Row="2" VerticalAlignment="Center" IsReadOnly="True" >
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource enumDescriptionConverter},ConverterParameter=Value}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
但是当我尝试绑定错误时,Value 以字符串“Value”的形式出现。有什么方法可以传递当前项目吗?
【问题讨论】:
-
我不清楚为什么你需要一个转换器参数。看起来您正在尝试在存在时生成
[Description]文本,否则生成枚举名称。枚举值应作为value参数进入Convert()。为什么在这种情况下需要额外的parameter? -
之前我使用的是string parameterString = parameter as string; var desc = (value.GetType().GetField(parameterString) ; 当我得到参数值时,我可以避免调用 Enum.GetName(value.GetType(), value);
标签: c# wpf combobox ivalueconverter