Привязать к указателю в коллекции Xamarin - PullRequest
0 голосов
/ 22 марта 2020

enter image description here

public List<Scoreboard> RawScoreboard { get; set; }

public ObservableCollection<Scoreboard> ScoreboardList { get; set; }


  <CollectionView ItemsSource="{Binding ScoreboardList}"
                        EmptyView="Sorry, no scores yet! Play a game and view your results here!">
            <CollectionView.ItemTemplate>
                <DataTemplate  x:DataType="models:Scoreboard">
                    <Grid BackgroundColor="{StaticResource BasePurple}">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="*" />
                        </Grid.ColumnDefinitions>

                        <Label Text="{Binding Score}" Style="{StaticResource LabelStyle}" />

                        <Label Grid.Column="1" Text="{Binding UserName}" Style="{StaticResource LabelStyle}" />

                        <Label Grid.Column="2" Text="{Binding CountryName}" Style="{StaticResource LabelStyle}" />

                        <Label Grid.Column="3" Style="{StaticResource LabelStyle}" >
                            <Label.FormattedText>
                                <FormattedString>
                                    <Span Text="{Binding Score}"/>
                                    <Span Text="/10"/>
                                </FormattedString>
                            </Label.FormattedText>
                        </Label>

                    </Grid>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>

Итак, я хочу изменить столбец Ранг, чтобы он связывался со своим собственным индексом в списке. Т.е. 1, 2, 3, 4, 5, 6. Просто нумерованный список здесь. Я думаю, что это может быть возможно сделать в linq, может быть?

public class Scoreboard
{
    public int UserId { get; set; }

    public int CountryId { get; set; }

    public string CountryName { get; set; }

    public string UserName { get; set; }

    public int Score { get; set; }
}

public async Task OnAppearing()
        {
            await GetScores();
            SortScoreboard();

            foreach (var scoreboard in RawScoreboard)
            {
                ScoreboardList.Add(scoreboard);
            }
    }

Я добавил весь соответствующий код, так что в основном. "Как мне связать элемент с его собственным индексом в представлении коллекции?"

1 Ответ

1 голос
/ 23 марта 2020

Это что-то вроде хака. Но вы можете создать 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>

Это как вы можете привязать свой Label к самому элементу и использовать ссылку в ConverterParameter для поиска индекса из:

<Label Text="{Binding ., Converter={StaticResource IndexConverter}, ConverterParameter={Binding Source={x:Reference Scores}, Path=BindingContext}}" />

Учитывая, что вы назвали свои CollectionView "Счеты" с помощью x:Name="Scores".

Это дает что-то вроде:

screenshot of test app

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...