C# 绑定到Xamarin集合中的索引

C# 绑定到Xamarin集合中的索引,c#,xaml,xamarin,xamarin.forms,C#,Xaml,Xamarin,Xamarin.forms,我已经添加了所有相关的代码,所以基本上。“如何将一个元素绑定到collectionview中它自己的索引?”这有点像一个黑客。但是您可以创建一个ValueConverter,它将CollectionView作为参数,并尝试从中获取索引: public class IndexValueConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, Cul


我已经添加了所有相关的代码,所以基本上。“如何将一个元素绑定到collectionview中它自己的索引?”

这有点像一个黑客。但是您可以创建一个ValueConverter,它将
CollectionView
作为参数,并尝试从中获取索引:

public class IndexValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (parameter is Binding binding && 
            value is Scoreboard score && 
            binding.Source is CollectionView collectionView && 
            collectionView.BindingContext is ScoreboardViewModel viewModel)
        {
            return viewModel.ScoreboardList.IndexOf(score);
        }

        return -1;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException();
}
请记住注册转换器:

<ContentPage.Resources>
    <ResourceDictionary>
        <converters:IndexValueConverter x:Key="IndexConverter" />
    </ResourceDictionary>
</ContentPage.Resources>
假设您使用
x:Name=“Scores”
调用了您的
CollectionView
“Scores”

这会产生如下结果:


a好的,唯一的方法是在记分卡中添加索引属性,或者创建自己的集合类型来维护自己的索引属性。乍一看似乎很简单,这听起来很复杂(虽然这是一个惊人的黑客!非常简单易用,谢谢你。我相信这会帮助很多其他开发者,在互联网上确实没有任何解决方案。
public class IndexValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (parameter is Binding binding && 
            value is Scoreboard score && 
            binding.Source is CollectionView collectionView && 
            collectionView.BindingContext is ScoreboardViewModel viewModel)
        {
            return viewModel.ScoreboardList.IndexOf(score);
        }

        return -1;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException();
}
<ContentPage.Resources>
    <ResourceDictionary>
        <converters:IndexValueConverter x:Key="IndexConverter" />
    </ResourceDictionary>
</ContentPage.Resources>