首页 > 解决方案 > 如何使用 ItemsSource 中每个项目的索引对 Xamarin.Forms ListView 中的项目进行编号,包括何时删除项目?

问题描述

我有一个转换器,它将 ListView 作为参数,将每个项目作为列表,然后,使用 ItemsSource 和 IndexOf,我可以确定列表中的项目位置并将其作为视图的数字返回:

public class MyConverter : IValueConverter, IMarkupExtension
{
     public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
     {
         var listView = parameter as ListView;
         var collection = listView.ItemsSource as IList;
         object item = value;

         var answer = collection.Count - collection.IndexOf(item); //I'm actually numbering items in reverse.
         return answer;
     }
}

我使用整个绑定上下文 ( {Binding .}) 绑定到它,以便将每个项目作为值传递给它自己的转换器,如下所示:

<ListView x:Name="ListViewItself" ItemsSource="{Binding TheItemSource}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Label Text="{Binding ., Converter={converters:MyConverter}, ConverterParameter={x:Reference ListViewItself}}" />
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

这很好用。当我将项目添加到列表中时,转换器会正确计算正确的项目位置。

我现在的问题是,当我从集合和 ListView 中删除项目时,ListView 中每个剩余项目的值应该自动更新,以便考虑它们的新位置。但这种情况并非如此。转换器被调用,但项目有许多空值。

我想知道,如何为列表中的每个绑定上下文调用 RaisePropertyChanged 以便转换器为所有这些上下文正确触发?

编辑:当我从集合中删除一个项目时, 我尝试使用 RaisePropertyChanged(nameof(TheItemSource))它,但它不会像我期望的那样为每个项目触发转换器。

标签: xamllistviewxamarin.formsbinding

解决方案


推荐阅读