This is a weird error. I'm binding an enum to a combo box and displaying the description attribute. I'm using the solution at WPF Binding a ListBox to an enum, displaying the Description Attribute. So the relevant part of my XAML is:
<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>
Then my code is:
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();
}
}
Now the weird part. I start the program and select a value from the combo box (this step is important). All works as expected. Then I connect to the computer via remote desktop. Immediately I get a NullReferenceException on the first line of the Convert()
function. The Type
parameter is a string, but otherwise there is not much information to troubleshoot, and the call stack is empty.