Home > database >  WPF Converter: Unable to cast object of type 'System.Int32' to type 'System.Windows.C
WPF Converter: Unable to cast object of type 'System.Int32' to type 'System.Windows.C

Time:03-23

In a GridViewColumn I have below converter:

<GridViewColumn Header="Number"
                DisplayMemberBinding="{Binding (ItemsControl.AlternationIndex), 
                                       RelativeSource={RelativeSource AncestorType=ListViewItem},
                                       Converter={StaticResource IndexConverter}, 
                                       ConverterParameter=1}"/>

This column is an auto-incremental index starting from 1 and the converter is:

public class IndexConverter : IValueConverter
{
    public object Convert(object value, Type TargetType, object parameter, CultureInfo culture)
    {
        ListViewItem item = (ListViewItem) value;
        ListView listView = ItemsControl.ItemsControlFromItemContainer(item) as ListView;
        int index = listView.ItemContainerGenerator.IndexFromContainer(item);

        if (Int32.TryParse(parameter as string, out int paramValue))
        {
            index  = paramValue;
        }

        return index.ToString();
    }

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

I am getting below compilation error:

Unable to cast object of type 'System.Int32' to type 'System.Windows.Controls.ListViewItem'

So xaml view is crashing.

CodePudding user response:

ItemsControl.AlternationIndex is not a ListViewItem but an int.

Try to bind to the ListViewItem itself if that's what your converter expects:

DisplayMemberBinding="{Binding Path=., 
    RelativeSource={RelativeSource AncestorType=ListViewItem},
    Converter={StaticResource IndexConverter}, 
    ConverterParameter=1}"
  • Related