1
votes

On Login or Navigating to any Page, fetching data from API, I am using an extra button (Show Communities) to fetch my Fetch my Data. here is my code

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:viewModels="clr-namespace:epolleasy.ViewModels;assembly=epolleasy"
         x:Class="epolleasy.Views.DpCommunities">

<ContentPage.BindingContext>
    <viewModels:DashboardViewModel />
</ContentPage.BindingContext>


<StackLayout>

    <Button Command="{Binding GetDashboard}" Text="Show Communities"/>

    <ListView ItemsSource="{Binding UserDashboard.Com}"
              HasUnevenRows="True">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <StackLayout>
                        <Label Text="{Binding CommunityName}"/>
                        <Label Text="{Binding CommunityUsers.Count}"/>
                        <Label Text="{Binding FormsCommunity.Count}"/>
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>

    </ListView>

</StackLayout>



</ContentPage>

Here is GetDashboard Command in my ViewModel

public ICommand GetDashboard
{
    get
    {
        return new Command(async () =>
        {
             var accessToken = Settings.AccessToken;
             UserDashboard = await _apiServices.GetDashboard(accessToken);
        });
    }

}

Here is my UserDashboard in the same view model.

public Dashboard UserDashboard
    {
        get { return _userDashboard; }
        set
        {
            _userDashboard = value;
            OnPropertyChanged();
        }
    } 

I want to get rid of that extra button.

2

2 Answers

1
votes

get your data in the OnAppearing method

void async override OnAppearing() 
{
   // call VM GetData method
}
0
votes

As I can see from these small code snippets that you are provided and what I can conclude... you are binding your ListView to some List or ObservableCollection, and when Command is "triggered" (on button click) you are calling the WebApi.

To remove usage of the button: You can use that code where you are calling the web api and you can put it inside of your ViewModel constructor, so in that case you making it easy and Web Api will be called automatically on creating your ViewModel and your List or ObservableCollection will be populated, and if you are "respecting" the MVVM in the right way your ListView will be updated correctly with your data from api.


This is my opinion and this approach will work, question for community is: "Is it a good practice to do like this?"... But as I said this will work for you, and you will not have the need for that Button.

P.S. Next time include all your classes that are relevant not just small methods, when you include all code we can see situation that you have and we can help you