views:

124

answers:

1

This is my class that implements IValueConverter:

[ValueConversion(typeof(int), typeof(Priority))]
public class PriorityConverter : IValueConverter
{

    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (Priority) (int) value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

It seems that this line of code throws an InvalidCastException:

return (Priority) (int) value;

(Priority being an enum) I put a breakpoint at the start of the method and the value of "value" is int:4 so I have no idea why this exception is being thrown. Here are resources (where app_data="clr-namespace:AssignmentOrganizer.App_Data"):

<app_data:PriorityConverter x:Key="PriorityConverter" />
<app_data:KindConverter x:Key="KindConverter" />

Here is the implementation:

<gridview:GridViewDataColumn Header="Priority" Width="100" DataMemberBinding="{Binding Priority, Converter={StaticResource PriorityConverter}}" />
<gridview:GridViewDataColumn Header="Kind" Width="100" DataMemberBinding="{Binding Kind, Converter={StaticResource KindConverter}}" />
+1  A: 

As discussed in the comments to the question, this occurs because what is actually being passed to your value converter is a Byte rather than an Int32. Unboxing casts must always be to the exact type; to determine that exact type, it's worth checking value.GetType().Name using Debug.WriteLine or the Immediate window.

itowlson