【发布时间】:2017-11-23 16:22:59
【问题描述】:
这是一个奇怪的错误。我将枚举绑定到组合框并显示描述属性。我正在使用WPF Binding a ListBox to an enum, displaying the Description Attribute 的解决方案。所以我的 XAML 的相关部分是:
<Window.Resources>
<local:EnumConverter x:Key="EnumConverter"/>
<ObjectDataProvider MethodName="GetValues"
ObjectType="{x:Type local:MyEnum}"
x:Key="MyEnumValues">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:MyEnum" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<ComboBox Name="MyComboBox" ItemsSource="{Binding Source={StaticResource MyEnumValues}}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource EnumConverter}}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
那么我的代码是:
public enum MyEnum
{
[Description("foo")]
Foo,
[Description("bar")]
Bar
}
public class EnumConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
FieldInfo field_info = value.GetType().GetField(value.ToString());
object[] attributes = field_info.GetCustomAttributes(false);
if (attributes.Length == 0)
return value.ToString();
else
{
DescriptionAttribute attribute = attributes[0] as DescriptionAttribute;
return attribute.Description;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
现在是奇怪的部分。我启动程序并从组合框中选择一个值(这一步很重要)。一切都按预期工作。然后我通过远程桌面连接到计算机。我立即在Convert() 函数的第一行得到一个 NullReferenceException。 Type参数是一个字符串,否则排查的信息不多,调用堆栈为空。
【问题讨论】:
-
在此处添加调试语句并告诉我们,它是对象还是 null 值?然后查看堆栈跟踪并向后查找原因。对象类型是什么?
-
@JohnPeters
value函数的Convert()参数为 null,这会导致异常。EnumConverter.Convert()是堆栈跟踪中唯一的东西。 -
好的,转换器是在 WPF 渲染时调用的,那么 Object 类型是什么?你能展示 XAML 部分....和绑定集合吗?
-
@JohnPeters 所有重要的 XAML 和代码都显示在上面。我没有包括的任何内容都只是自动生成的样板。
标签: c# .net wpf remote-desktop ivalueconverter