WPF 转换器:无法将类型 'System.Int32' 的对象转换为类型 'System.Windows.Controls.ListViewItem'

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

在 GridViewColumn 中,我有以下转换器:

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

该列为自增索引,从1开始,转换器为:

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();
    }
}

我遇到以下编译错误:

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

所以 xaml 视图崩溃了。

ItemsControl.AlternationIndex 不是 ListViewItem,而是 int

尝试绑定到 ListViewItem 本身,如果这是您的转换器所期望的:

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