Listview не привязан к начальной нагрузке, но работает на RefreshCommand в форме xamarin - PullRequest
0 голосов
/ 29 января 2020

Мой ListView не загружает данные для клиентов, так как приложение открыто, но работает нормально, когда я провожу сверху вниз, вызывая команду RefreshCommand.

ClientViewModel.cs

public class ClientViewModel : BaseViewModel
    {
        private ObservableCollection<Client> _clients { get; set; }
        private IClientManager ClientManager { get; }
        public ClientViewModel(INavigationManager navigationManager, IClientManager clientManager)
            :base(navigationManager)
        {
            Title = "Client";
            Clients = new ObservableCollection<Client>();
            ClientManager = clientManager;
        }

        public ObservableCollection<Client> Clients 
        {
            get => _clients;
            set
            {
                _clients = value;
                OnPropertyChanged();
            }
        }

        public Command LoadClientsCommand => new Command(async () => await ExecuteLoadClientsCommand());

        public Command SelectedItemCommand => new Command<Client>(OnClientSelected);

        //public Command AddClientCommand => new Command(() => OpenClientAddPage());

        private void OnClientSelected(Client obj)
        {
            NavigationManager.NavigateToAsync<ClientDetailViewModel>(obj);
        }

        public override async Task InitializeAsync(object data)
        {
            await ExecuteLoadClientsCommand();
        }

        private async Task ExecuteLoadClientsCommand()
        {
            if (IsBusy)
                return;

            IsBusy = true;

            try
            {
                Clients.Clear();
                Clients = (await ClientManager.GetAllClient()).ToObservableCollection();
            }
            catch (System.Exception)
            {
                throw;
            }
            finally
            {
                IsBusy = false;
            }
        }
    }

ClientPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:local="clr-namespace:Scheduler.Behaviours"
             xmlns:localconverter="clr-namespace:Scheduler.Converters"
             mc:Ignorable="d"
             xmlns:utility="clr-namespace:Scheduler.Utility;assembly=Scheduler"
                  utility:ViewModelLocator.AutoWireViewModel="True"
             Title="{Binding Title}"
             x:Class="Scheduler.Views.ClientPage">
    <ContentPage.Resources>
        <ResourceDictionary>
            <localconverter:SelectedItemConverter x:Key="SelectedClient" />
        </ResourceDictionary>
    </ContentPage.Resources>

    <ContentPage.ToolbarItems>
        <ToolbarItem Text="Add"/>
    </ContentPage.ToolbarItems>

    <StackLayout>
        <ListView x:Name="ClientListView"
                  ItemsSource="{Binding Clients}"
                  VerticalOptions="FillAndExpand"
                  HasUnevenRows="true"
                  RefreshCommand="{Binding LoadClientsCommand}"
                  IsPullToRefreshEnabled="True"
                  IsRefreshing="{Binding IsBusy, Mode=OneWay}"
                  CachingStrategy="RecycleElement">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <!--<ViewCell.ContextActions>
                            <MenuItem Clicked="OnDelete_Clicked" Text="Delete" CommandParameter="{Binding .}"/>
                        </ViewCell.ContextActions>-->
                        <StackLayout Padding="10">
                                   <Label Text="{Binding FullName}"
                                   d:Text="{Binding .}"
                                   LineBreakMode="NoWrap"
                                   Style="{DynamicResource ListItemTextStyle}" />
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
            <ListView.Behaviors>
                <local:EventToCommandBehaviour EventName="ItemSelected" 
                                               Command="{Binding SelectedItemCommand}" 
                                               Converter="{StaticResource SelectedClient}" />
            </ListView.Behaviors>
        </ListView>
    </StackLayout>
</ContentPage>

1 Ответ

2 голосов
/ 29 января 2020

Во-первых, вы дважды вызываете один и тот же API здесь

Clients.Clear();
await ClientManager.GetAllClient();
Clients = (await ClientManager.GetAllClient()).ToObservableCollection();

это может буквально быть похоже на

Clients.Clear();
Clients = (await ClientManager.GetAllClient()).ToObservableCollection();

Во-вторых, я не вижу, чтобы вы вызывали один и тот же API в конструктор в том случае, откуда данные? Я бы посоветовал вам сделать указанный выше вызов API на предыдущей странице и передать его здесь!

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