Xamarin - Группировка просмотров списка - PullRequest
0 голосов
/ 23 марта 2020

У меня возникли проблемы с группировкой списков. Когда я isgroupingenabled = "true" в моем списке отображается только имя groupDisplayBinding.

Я прочитал и перепробовал много вещей и не смог применить их в своем проекте, мне нужна ваша помощь сейчас.

Я видел, что мне нужно поставить Observablecollection, но я не знаю, где и как это сделать.

Моя модель

        public class League
    {
        public string name { get; set; }
        public string country { get; set; }
        public string logo { get; set; }
        public string flag { get; set; }
    }

    public class HomeTeam
    {
        public int team_id { get; set; }
        public string team_name { get; set; }
        public string logo { get; set; }
    }

    public class AwayTeam
    {
        public int team_id { get; set; }
        public string team_name { get; set; }
        public string logo { get; set; }
    }

    public class Score
    {
        public string halftime { get; set; }
        public string fulltime { get; set; }
        public string extratime { get; set; }
        public string penalty { get; set; }
    }

    public class Fixture
    {
        public int fixture_id { get; set; }
        public int league_id { get; set; }
        public League league { get; set; }
        public DateTime event_date { get; set; }
        public int event_timestamp { get; set; }
        public int? firstHalfStart { get; set; }
        public int? secondHalfStart { get; set; }
        public string round { get; set; }
        public string status { get; set; }
        public string statusShort { get; set; }
        public int elapsed { get; set; }
        public string venue { get; set; }
        public string referee { get; set; }
        public HomeTeam homeTeam { get; set; }
        public AwayTeam awayTeam { get; set; }
        public int? goalsHomeTeam { get; set; }
        public int? goalsAwayTeam { get; set; }
        public Score score { get; set; }
    }

    public class Api
    {
        public int results { get; set; }
        public List<Fixture> Fixtures { get; set; }
    }

    public class RootFixtures
    {
        public Api api { get; set; }
    }

Мой JSON: (Часть этого)

{"api": {
"results": 162,
"fixtures": [
  {
    "fixture_id": 234670,
    "league_id": 900,
    "league": {
      "name": "Division 1",
      "country": "Saudi-Arabia",
      "logo": null,
      "flag": "https://media.api-sports.io/flags/sa.svg"
    },
    "event_date": "2020-03-10T00:00:00+00:00",
    "event_timestamp": 1583798400,
    "firstHalfStart": null,
    "secondHalfStart": null,
    "round": "Regular Season - 28",
    "status": "Match Postponed",
    "statusShort": "PST",
    "elapsed": 0,
    "venue": "Prince Saud bin Jalawi Stadium (al-Khobar (Khobar))",
    "referee": null,
    "homeTeam": {
      "team_id": 2933,
      "team_name": "Al-Qadisiyah FC",
      "logo": "https://media.api-sports.io/teams/2933.png"
    },
    "awayTeam": {
      "team_id": 2928,
      "team_name": "Al Khaleej Saihat",
      "logo": "https://media.api-sports.io/teams/2928.png"
    },
    "goalsHomeTeam": null,
    "goalsAwayTeam": null,
    "score": {
      "halftime": null,
      "fulltime": null,
      "extratime": null,
      "penalty": null
    }
  }
]

}}

ListMatchPage:

    public partial class ListMatchs : ContentPage
{
    string JsonLeagues = "The Json Below"
    public ListMatchs()
    {
        InitializeComponent();

        var Leagues = JsonConvert.DeserializeObject<RootFixtures>(JsonLeagues);

        LeaguesList.ItemsSource = Leagues.api.Fixtures;

    }
}

Я новичок в dev, и я надеюсь, что мой engli sh был не так уж и плох. изменить: MyXAML:

 <ContentPage.Content>
    <StackLayout>
        <Label Text="Futurs matchs" HorizontalTextAlignment="Center" />
        <ListView x:Name="LeaguesList" GroupDisplayBinding="{Binding Path=League.name}"
                  GroupShortNameBinding="{Binding Path=League.name}"
                  IsGroupingEnabled="True" HasUnevenRows="True">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell Height="30">
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="*"/>
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="20"/>
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="20" />
                            </Grid.ColumnDefinitions>
                            <Image Grid.Column="0" Aspect="AspectFit" Source="{Binding Path=homeTeam.logo}" />
                            <Label Grid.Column="1" VerticalOptions="CenterAndExpand" HorizontalTextAlignment="Center" TextColor="Black" FontSize="15" FontAttributes="Bold" Text="{Binding Path=homeTeam.team_name}" HorizontalOptions="CenterAndExpand"/>
                            <Label Grid.Column="2" VerticalOptions="CenterAndExpand" HorizontalTextAlignment="Center" TextColor="Black" FontSize="15" FontAttributes="Bold" Text="{Binding Path=awayTeam.team_name}" HorizontalOptions="CenterAndExpand"/>
                            <Image Grid.Column="3" Aspect="AspectFit" Source="{Binding Path=awayTeam.logo}" />
                        </Grid>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage.Content>

Ответы [ 2 ]

0 голосов
/ 25 марта 2020

@ JackHUA вот что я сделал:

XAML.CS :



    ObservableCollection<groupedfix> FixturesCollection = new ObservableCollection<groupedfix>();
public ListMatchs()
        {

            InitializeComponent();

            var Leagues = JsonConvert.DeserializeObject<RootFixtures>(JsonLeagues);
            foreach (var match in Leagues.api.Fixtures)

            {
                int fixtureid = match.fixture_id;
                DateTime fixturedate = match.event_date;

                int FixtureLeagueid = match.league_id;
                string FixtureLeague = match.league.name;
                string FixtureLeaguelogo = match.league.logo;

                string Hometeamname = match.homeTeam.team_name;
                string Hometeamlogo = match.homeTeam.logo;
                string Awayteamname = match.awayTeam.team_name;
                string Awayteamlogo = match.awayTeam.logo;

                HomeTeam HOMETEAM = new HomeTeam() { team_name = Hometeamname, logo = Hometeamlogo };
                AwayTeam AWAYTEAM = new AwayTeam() { team_name = Awayteamname, logo = Awayteamlogo };
                League LEAGUE = new League() { logo = FixtureLeaguelogo, name = FixtureLeague };

                Fixture MATCH = new Fixture() { fixture_id = fixtureid, event_date = fixturedate, league_id = FixtureLeagueid, league = LEAGUE, homeTeam = HOMETEAM, awayTeam = AWAYTEAM };

                groupedfix GROUPEDFIX = new groupedfix(FixtureLeague) { MATCH };

                FixturesCollection.Add(GROUPEDFIX);

            }

            LeaguesList.ItemsSource = FixturesCollection;

        }


        public class groupedfix : List<Fixture>
        {
            public string FixtureLeague { get; set; }

            public groupedfix(string Name )
            {
                FixtureLeague = Name;

            }

        }

XAML:

    <ContentPage.Content>
    <StackLayout>
        <Label Text="Futurs matchs" HorizontalTextAlignment="Center" />
        <ListView x:Name="LeaguesList" GroupDisplayBinding="{Binding FixtureLeague}"
                  IsGroupingEnabled="True" HasUnevenRows="True" ItemTapped="Newgameclick">
            <ListView.ItemTemplate>
                <DataTemplate> 
                    <ViewCell Height="30">
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="*"/>
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="20"/>
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="20" />
                            </Grid.ColumnDefinitions>
                            <Image Grid.Column="0" Aspect="AspectFit" Source="{Binding Path=homeTeam.logo}"/>
                            <Label Grid.Column="1" VerticalOptions="CenterAndExpand" HorizontalTextAlignment="Center" TextColor="Black" FontSize="15" FontAttributes="Bold" Text="{Binding Path=homeTeam.team_name}" HorizontalOptions="CenterAndExpand"/>
                            <Label Grid.Column="2" VerticalOptions="CenterAndExpand" HorizontalTextAlignment="Center" TextColor="Black" FontSize="15" FontAttributes="Bold" Text="{Binding Path=awayTeam.team_name}" HorizontalOptions="CenterAndExpand"/>
                            <Image Grid.Column="3" Aspect="AspectFit" Source="{Binding Path=awayTeam.logo}" />
                        </Grid>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage.Content>

Результат изображения: См. Пи c

Но когда я меняю

LeaguesList.ItemsSource = FixturesCollection;

в

LeaguesList.ItemsSource = FixturesCollection.GroupBy(F => F.FixtureLeague);

, я получаю это: См. Пи c

С ошибкой:

[0:] Binding:'FixtureLeague' property not found on 'System.Linq.Grouping`2[System.String,BeastTIPS.Pages.ListMatchs+groupedfix]'...
        [0:] Binding: 'homeTeam' property not found on 'BeastTIPS.Pages.ListMatchs+groupedfix'...
    [0:] Binding: 'awayTeam' property not found on 'BeastTIPS.Pages.ListMatchs+groupedfix'...

Список сгруппирован, но моя привязка не найдена. Я не могу найти какое свойство для привязки.

0 голосов
/ 24 марта 2020

Модель, которую вы добавили в ItemsSource, должна быть в правильном формате в качестве документа , упомянутого , я написал для вас пример, и вы можете проверить код:

public partial class MainPage : ContentPage
{
    ObservableCollection<myModel> FixtureCollection = new ObservableCollection<myModel>();
    public MainPage()
    {
        InitializeComponent();

        League LeagueOne = new League() { name = "one" };
        League LeagueTwo = new League() { name = "two" };
        League LeagueThree = new League() { name = "three" };

        HomeTeam HomeTeamOne = new HomeTeam() { team_name = "HomeTeamOne" };
        HomeTeam HomeTeamTwo = new HomeTeam() { team_name = "HomeTeamTwo" };
        HomeTeam HomeTeamThree = new HomeTeam() { team_name = "HomeTeamThree" };

        AwayTeam AwayTeamOne = new AwayTeam() { team_name = "AwayTeamOne" };
        AwayTeam AwayTeamTwo = new AwayTeam() { team_name = "AwayTeamTwo" };
        AwayTeam AwayTeamThree = new AwayTeam() { team_name = "AwayTeamThree" };


        Fixture FixtureOne = new Fixture() { league = LeagueOne, homeTeam = HomeTeamOne, awayTeam = AwayTeamOne};
        Fixture FixtureTwo = new Fixture() { league = LeagueTwo, homeTeam = HomeTeamTwo, awayTeam = AwayTeamTwo };
        Fixture FixtureThree = new Fixture() { league = LeagueThree, homeTeam = HomeTeamThree, awayTeam = AwayTeamThree };


        myModel myModelOne = new myModel(FixtureOne.league.name) { FixtureOne };
        myModel myModelTwo = new myModel(FixtureTwo.league.name) { FixtureTwo };
        myModel myModelThree = new myModel(FixtureThree.league.name) {FixtureThree };

        FixtureCollection.Add(myModelOne);
        FixtureCollection.Add(myModelTwo);
        FixtureCollection.Add(myModelThree);

        LeaguesList.ItemsSource = FixtureCollection;

        BindingContext = this;
    }
}

public class myModel : List<Fixture>
{
    public string name { get; set; }
    public myModel( string Name) {
        name = Name;
    }
}

И в код:

<StackLayout>
    <Label Text="Futurs matchs" HorizontalTextAlignment="Center" />
    <ListView x:Name="LeaguesList" 
              GroupDisplayBinding="{Binding name}"
              GroupShortNameBinding="{Binding name}"
              IsGroupingEnabled="True" HasUnevenRows="True">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell Height="30">
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="*"/>
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="20"/>
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="20" />
                        </Grid.ColumnDefinitions>
                        <Image Grid.Column="0" Aspect="AspectFit" Source="{Binding Path=homeTeam.logo}" />
                        <Label Grid.Column="1" VerticalOptions="CenterAndExpand" HorizontalTextAlignment="Center" TextColor="Black" FontSize="15" FontAttributes="Bold" Text="{Binding Path=homeTeam.team_name}" HorizontalOptions="CenterAndExpand"/>
                        <Label Grid.Column="2" VerticalOptions="CenterAndExpand" HorizontalTextAlignment="Center" TextColor="Black" FontSize="15" FontAttributes="Bold" Text="{Binding Path=awayTeam.team_name}" HorizontalOptions="CenterAndExpand"/>
                        <Image Grid.Column="3" Aspect="AspectFit" Source="{Binding Path=awayTeam.logo}" />
                    </Grid>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</StackLayout>

Я также загрузил свой пример проекта здесь и не стесняйтесь задавать мне любые вопросы.

Обновление:

Я думаю, что вам действительно нужно OrderBy, а не GroupBy:

LeaguesList.ItemsSource = FixturesCollection.OrderBy(f => f.FixtureLeague).ToList();

Когда вы используете GroupBy, вы можете установить точку останова прямо там, чтобы проверить LeaguesList.ItemsSource, вы обнаружит, что структура была изменена, число LeaguesList.ItemsSource становится 56.

В вашем xaml есть еще одна проблема, GroupDisplayBinding должен связываться с FixtureLeague, а не с именем:

<ListView x:Name="LeaguesList" GroupDisplayBinding="{Binding FixtureLeague}"
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...