這是一個奇怪的錯誤。我將枚舉綁定到組合框並顯示description屬性。我使用的解決方案是WPF Binding a ListBox to an enum, displaying the Description Attribute。所以,我的XAML的相關部分是:通過遠程桌面連接時,帶IValueConverter的NullReferenceException
<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'Convert()'函數的'value'參數爲空,導致異常。 'EnumConverter.Convert()'是堆棧跟蹤中唯一的東西。 –
好的,轉換器在WPF渲染時調用,那麼對象類型是什麼?你可以顯示XAML部分....和綁定集合嗎? –