How to open a page from a class? - xamarin

I am trying to create a little application using MVVM. I would like to open a second page that scan a QR code and then back the value of the QR code to the main page.
I have this code:
Main view:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="QRScannerXamarinForms.Views.MainPageView"
xmlns:zxing="clr-namespace:ZXing.Net.Mobile.Forms;assembly=ZXing.Net.Mobile.Forms"
xmlns:vm="clr-namespace:QRScannerXamarinForms.ViewModels">
<ContentPage.BindingContext>
<vm:MainPageViewModel/>
</ContentPage.BindingContext>
<StackLayout>
<Frame BackgroundColor="#2196F3" Padding="24" CornerRadius="0">
<Label Text="Barcode Sample" HorizontalTextAlignment="Center" TextColor="White" FontSize="36" />
</Frame>
<Button x:Name="ucBtnEscanear" Text="Escanear"
Command="{Binding EscanearCommand}"/>
</StackLayout>
</ContentPage>
Main view model:
private INavigationService _navigationService;
public ICommand EscanearCommand { get; private set; }
private void Escanear()
{
string miCodigoQr = _navigationService.AbrirPaginaEscaner();
}
Second view:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="QRScannerXamarinForms.Views.ScannerView"
xmlns:zxing="clr-namespace:ZXing.Net.Mobile.Forms;assembly=ZXing.Net.Mobile.Forms"
xmlns:vm="clr-namespace:QRScannerXamarinForms.ViewModels">
<ContentPage.BindingContext>
<vm:ScannerViewModel/>
</ContentPage.BindingContext>
<ContentPage.Content>
<StackLayout>
<Frame BackgroundColor="#2196F3" Padding="24" CornerRadius="0">
<Label Text="Barcode Sample" HorizontalTextAlignment="Center" TextColor="White" FontSize="36" />
</Frame>
<Label x:Name="ucScanResultText" />
<zxing:ZXingScannerView x:Name="ucZXingScannerView" IsScanning="True" IsAnalyzing="True" Result="{Binding CodigoQr}" />
</StackLayout>
</ContentPage.Content>
</ContentPage>
Second view model:
class ScannerViewModel : BaseViewModel
{
private string _codigoQr;
public string CodigoQr
{
get { return _codigoQr; }
set { _codigoQr = value; }
}
}
Interface to open pages:
namespace QRScannerXamarinForms.Services
{
interface INavigationService
{
string AbrirPaginaEscaner();
}
}
Implementation of the interface that allows navigation.
namespace QRScannerXamarinForms.Services
{
class ViewNavigationService : INavigationService
{
public string AbrirPaginaEscaner()
{
ScannerView miScannerView = new ScannerView();
ScannerViewModel miScannerViewModel = miScannerView.BindingContext as ScannerViewModel;
Application.Current.MainPage.Navigation.PushModalAsync(miScannerView);
return miScannerViewModel.CodigoQr;
}
}
}
But in the implementation of the interface, the second page is not shown. So this line doesn't work:
Application.Current.MainPage.Navigation.PushModalAsync(miScannerView);
How could I open from this class?
Thanks.

Related

ZXing QRCode Scanner Xamarin

I tried to implement the package ZXing.Net.Mobile.Forms
this is my xaml:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:zxing="clr-namespace:ZXing.Net.Mobile.Forms;assembly=ZXing.Net.Mobile.Forms"
Title="{Binding Title}">
<ContentPage.Content>
<StackLayout>
<Label x:Name="scanResultText" />
<zxing:ZXingScannerView
OnScanResult="ScanViewOnScanResult"/>
</StackLayout>
</ContentPage.Content>
and this my xaml.cs :
public partial class QRCodePage : ContentPage
{
public QRCodePage()
{
InitializeComponent();
BindingContext = new QRCodeViewModel();
}
public void ScanViewOnScanResult(Result result)
{
Device.BeginInvokeOnMainThread(async () =>
{
scanResultText.Text = result.Text;
});
}
}
On my device i visualize the fragment but it seems not scanning
Try adding the following code (IsScanning="True") to your xaml:
<StackLayout>
<Label x:Name="scanResultText" />
<zxing:ZXingScannerView IsScanning="True"
OnScanResult="ScanViewOnScanResult"/>
</StackLayout>

How to share View Model between pages?

I can add data to the viewmodel, but when I try to access the same viewmodel from another page, the data is lost. How can I use the same viewmodel across multiple pages?
ViewModel Code
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Windows.Input;
using Xamarin.Forms;
namespace App1
{
class DebtViewModel
{
ObservableCollection<Debt> _Debt = new ObservableCollection<Debt>();
public System.Windows.Input.ICommand AddAccountCommand => new Command(AddAccount);
public System.Windows.Input.ICommand RemoveAccountCommand => new Command(RemoveAccount);
public System.Windows.Input.ICommand UpdateAccountCommand => new Command(UpdateAccount);
public ObservableCollection<Debt> Debt { get; set; }
public string Account { get; set; }
public string SelectedAccount { get; set; }
public double AnnualPercentageRate { get; set; }
public decimal Amount { get; set; }
public decimal MonthlyPayment { get; set; }
public bool IntroductoryRate { get; set; }
public double IntroductoryPercentageRate { get; set; }
public int IntroductoryRange { get; set; }
public DebtViewModel()
{
ObservableCollection<Debt> Debts = _Debt;
}
public void AddAccount()
{
var debt = new Debt(Account, Amount, AnnualPercentageRate, MonthlyPayment, IntroductoryRate,
IntroductoryPercentageRate, IntroductoryRange);
if (Account != null)
{
_Debt.Add(debt);
}
}
public void RemoveAccount()
{
//Debt.Remove(SelectedAccount);
}
public void UpdateAccount()
{
//int newIndex = Debt.IndexOf(SelectedAccount);
//Debt.Remove(SelectedAccount);
//Debt.Add(Account);
//int oldIndex = Debt.IndexOf(Account);
//Debt.Move(oldIndex, newIndex);
}
}
}
List Page
<?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:App1"
mc:Ignorable="d"
x:Class="App1.ListViewPage">
<!-- Required to map viewmodel -->
<ContentPage.BindingContext>
<local:DebtViewModel />
</ContentPage.BindingContext>
<ContentPage.ToolbarItems>
<ToolbarItem Text="Add"></ToolbarItem>
</ContentPage.ToolbarItems>
<!-- Bind variable in view model to listview itemsource -->
<ContentPage.Content>
<StackLayout>
<!--<Entry Placeholder="Account"
Text="{Binding Account}"/>
<Button Text="Add" Command="{Binding AddAccountCommand}"></Button>
<Button Text="Remove" Command="{Binding RemoveAccountCommand}"></Button>
<Button Text="Update" Command="{Binding UpdateAccountCommand}"></Button>-->
<!--textcell, custom cells, or image cell-->
<ListView ItemsSource="{Binding Debt}" SelectedItem="{Binding SelectedAccount}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="3*" />
</Grid.ColumnDefinitions>
<Label Text="{Binding AccountName}"
FontSize="Medium"
VerticalTextAlignment="Start"
Grid.Column="0"></Label>
<Label Text="Balance"
VerticalTextAlignment="Start"
Grid.Column="1"></Label>
<Label Text="{Binding InitialAmount}"
VerticalTextAlignment="End"
Grid.Column="1"></Label>
<Label Text="APR"
VerticalTextAlignment="Start"
Grid.Column="2"></Label>
<Label Text="{Binding AnnualPercentageRate}"
VerticalTextAlignment="End"
Grid.Column="2"></Label>
<Label Text="Monthly Payment"
VerticalTextAlignment="Start"
Grid.Column="3"></Label>
<Label Text="{Binding MonthlyPayment}"
VerticalTextAlignment="End"
Grid.Column="3"></Label>
<Image Source="edit.png" Grid.Column="4"></Image>
<Image Source="trash.jpg" Grid.Column="5"></Image>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
</ContentPage>
Add Page
<?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:App1"
mc:Ignorable="d"
x:Class="App1.ListViewPage">
<!-- Required to map viewmodel -->
<ContentPage.BindingContext>
<local:DebtViewModel />
</ContentPage.BindingContext>
<ContentPage.ToolbarItems>
<ToolbarItem Text="Add"></ToolbarItem>
</ContentPage.ToolbarItems>
<!-- Bind variable in view model to listview itemsource -->
<ContentPage.Content>
<StackLayout>
<!--<Entry Placeholder="Account"
Text="{Binding Account}"/>
<Button Text="Add" Command="{Binding AddAccountCommand}"></Button>
<Button Text="Remove" Command="{Binding RemoveAccountCommand}"></Button>
<Button Text="Update" Command="{Binding UpdateAccountCommand}"></Button>-->
<!--textcell, custom cells, or image cell-->
<ListView ItemsSource="{Binding Debt}" SelectedItem="{Binding SelectedAccount}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="3*" />
</Grid.ColumnDefinitions>
<Label Text="{Binding AccountName}"
FontSize="Medium"
VerticalTextAlignment="Start"
Grid.Column="0"></Label>
<Label Text="Balance"
VerticalTextAlignment="Start"
Grid.Column="1"></Label>
<Label Text="{Binding InitialAmount}"
VerticalTextAlignment="End"
Grid.Column="1"></Label>
<Label Text="APR"
VerticalTextAlignment="Start"
Grid.Column="2"></Label>
<Label Text="{Binding AnnualPercentageRate}"
VerticalTextAlignment="End"
Grid.Column="2"></Label>
<Label Text="Monthly Payment"
VerticalTextAlignment="Start"
Grid.Column="3"></Label>
<Label Text="{Binding MonthlyPayment}"
VerticalTextAlignment="End"
Grid.Column="3"></Label>
<Image Source="edit.png" Grid.Column="4"></Image>
<Image Source="trash.jpg" Grid.Column="5"></Image>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
</ContentPage>
As Jason said: If you specify the VM in XAML it will create a new instance for each page. They are totally different.
How can I use the same viewmodel across multiple pages?
There are many ways to do it.
For example, you can define/create a static ViewModel in App.cs:
public partial class App : Application
{
public static DebtViewModel sharedViewModel { get; set; }
public App()
{
InitializeComponent();
MainPage = new MainPage();
createViewModel();
}
public void createViewModel() {
sharedViewModel = new DebtViewModel();
}
public class DebtViewModel {
}
}
Then in other page, you can set this ViewModel as page's bindingContext:
public partial class Page1 : ContentPage
{
public Page1()
{
InitializeComponent();
this.BindingContext = App.sharedViewModel;
}
}
Pass the instance to the new page on the constructor in also a solution.

How to make a local ContentView bind a Label text

I made a ContentView with an Expander. I want to duplicate this Xaml code multiple times in an other Xaml file. But I want for each Expander a different Binding.
I linked this code (ContentView code):
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:expandable="clr-namespace:Expandable;assembly=ExpandableView"
x:Class="Hello.ExpandableView">
<ContentView.Content>
<expandable:ExpandableView Padding="5">
<expandable:ExpandableView.PrimaryView>
<Frame BackgroundColor="White" Padding="5" CornerRadius="10">
<StackLayout Orientation="Horizontal">
<Label x:Name="label" FontSize="16" TextColor="Black" FontAttributes="Bold" Padding="5" HorizontalTextAlignment="Start" HorizontalOptions="StartAndExpand"/>
<Image Source="arrow.png" WidthRequest="25" HeightRequest="25" Margin="5"/>
</StackLayout>
</Frame>
</expandable:ExpandableView.PrimaryView>
<expandable:ExpandableView.SecondaryViewTemplate>
<DataTemplate>
<Frame BackgroundColor="White" Padding="5" CornerRadius="10">
<Label Text="{Binding Tip1Uitleg}" FontSize="15" TextColor="Black" Padding="5"/>
</Frame>
</DataTemplate>
</expandable:ExpandableView.SecondaryViewTemplate>
</expandable:ExpandableView>
</ContentView.Content>
</ContentView>
namespace Hello
{
public partial class ExpandableView : ContentView
{
public static BindableProperty LabelProperty =
BindableProperty.Create(nameof(Label),
typeof(string),
typeof(ExpandableView),
propertyChanged: (b, o, n) => (b as ExpandableView).OnLabelChanged());
private void OnLabelChanged()
{
label.Text = Label; //label is the x:Name of your Label control in ExpandableView.xaml
}
public string Label
{
get => (string)GetValue(LabelProperty);
set => SetValue(LabelProperty, value);
}
}
}
To this code:
This works:
<local:ExpandableView Label="Hello"/>
But I want this. This does not work:
<?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:expandable="clr-namespace:Expandable;assembly=ExpandableView"
xmlns:local="clr-namespace:Hello"
x:Class="Hello.Health.HealthDetail"
Title="{Binding Name}">
<ContentPage.Content>
<ScrollView>
<StackLayout>
<Image Source="{Binding Image}"/>
<Label Text="{Binding Tip1Uitleg}" FontSize="15" TextColor="Black" Padding="10, 5, 10, 5"/>
<local:ExpandableView Label="{Binding Tip1}"/> //This is what it is all about
</StackLayout>
</ScrollView>
</ContentPage.Content>
</ContentPage>
CodeBehind:
namespace Hello.Health
{
public partial class HealthDetail : ContentPage
{
public HealthDetail(HealthStrings healthStrings)
{
if (healthStrings == null)
throw new ArgumentNullException();
BindingContext = healthStrings;
InitializeComponent();
}
}
}
How do I make this work? I have to make this above more dynamic, but I do not know how.
BTW This also works:
<Label Text="{Binding Tip1}" />
I am sorry for the unclear explanation, I hope someone can help me.
Thank you for your time :)
You should not bind to 'this' since you are using a BindableProperty. Instead you should update the Label.Text property when the value of the BindableProperty changes.
public static BindableProperty LabelProperty =
BindableProperty.Create(nameof(Label),
typeof(string),
typeof(ExpandableView),
propertyChanged:(b, o, n) => (b as ExpandableView).OnLabelChanged());
private void OnLabelChanged()
{
label.Text = Label; //label is the x:Name of your Label control in ExpandableView.xaml
}
public string Label
{
get => (string)GetValue(LabelProperty);
set => SetValue(LabelProperty, value);
}
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="YourProject.ExpandableView">
<Grid>
<Label x:Name="label"/>
</Grid>
</ContentView>
Normally, when you want to binding a value for binableproperty, you could try the code below:
ExpandableView: I make a simple contentview with the same binableproperty for you reference.
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="XamarinDemo.Pages.ExpandableView">
<ContentView.Content>
<StackLayout>
<Label Text="Hello"></Label>
<Label x:Name="label"></Label>
</StackLayout>
</ContentView.Content>
</ContentView>
Code behind:
public partial class ExpandableView : ContentView
{
public static BindableProperty LabelProperty =
BindableProperty.Create(nameof(Label),
typeof(string),
typeof(ExpandableView),
propertyChanged: (b, o, n) => (b as
ExpandableView).OnLabelChanged());
private void OnLabelChanged()
{
label.Text = Label; //label is the x:Name of your Label control in ExpandableView.xaml
}
public string Label
{
get => (string)GetValue(LabelProperty);
set => SetValue(LabelProperty, value);
}
public ExpandableView()
{
InitializeComponent();
}
}
Usage:
<ContentPage.Content>
<local:ExpandableView Label="{Binding str}"></local:ExpandableView>
</ContentPage.Content>
Code Behind:
public partial class Page1 : ContentPage
{
public string str { get; set; }
public Page1()
{
InitializeComponent();
str = "okay";
this.BindingContext = this;
}
}

СarouselView does not display content

СarouselView does not display content. I have the following code in the AppShell.axml
for the whole day I can’t figure out how to make this work. Help make a working code.
<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"
mc:Ignorable="d"
xmlns:local="clr-namespace:test.Views"
BackgroundColor="Azure"
x:Class="test.AppShell">
<CarouselView HorizontalOptions="Center" NumberOfSideItems="1">
<CarouselView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Frame HasShadow="True"
BorderColor="DarkGray"
CornerRadius="5"
Margin="20"
HeightRequest="300"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand">
<StackLayout>
<Label Text="11111111111"
FontAttributes="Bold"
FontSize="Large"
HorizontalOptions="Center"
VerticalOptions="Center" />
</StackLayout>
</Frame>
</StackLayout>
</DataTemplate>
</CarouselView.ItemTemplate>
</CarouselView>
</ContentPage>
I have the following code in the AppShell.axml.cs
using System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace test
{
public partial class AppShell : ContentPage
{
public AppShell()
{
InitializeComponent();
}
}
}
I tried such an example and it works, but I need the option to work from above.
<CarouselView>
<CarouselView.ItemsSource>
<x:Array Type="{x:Type x:String}">
<x:String>Baboon</x:String>
<x:String>Capuchin Monkey</x:String>
<x:String>Blue Monkey</x:String>
<x:String>Squirrel Monkey</x:String>
<x:String>Golden Lion Tamarin</x:String>
<x:String>Howler Monkey</x:String>
<x:String>Japanese Macaque</x:String>
</x:Array>
</CarouselView.ItemsSource>
</CarouselView>
Firstly why you place a carsouselView in the Appshell.xaml? I think the AppShell.Xaml is only to set the App configurations.
you can write code in the AppShell.xaml to layout the App menu or flylayout.
if you do not specify a ItemsSource to CarouselView It will not renderer.
you can make the ItemsSource by BindingContext.
Do you want to achieve the result like following GIF?
If so, you could show the content in the CarouselView by DataBinding.
Step 1: Create a Model for your CarouselView, I create it like following code.
public class MyModel
{
public string Name { get; set; }
}
Step 2: create a viewModel for your CarouselView(we can add the content that we want them to display).
public class MyModelView: BaseViewModel
{
public ObservableCollection<MyModel> MyModels { get; set; }
public MyModelView()
{
MyModels = new ObservableCollection<MyModel>();
MyModels.Add(new MyModel() { Name="test1"});
MyModels.Add(new MyModel() { Name = "test2" });
MyModels.Add(new MyModel() { Name = "test3" });
MyModels.Add(new MyModel() { Name = "test4" });
MyModels.Add(new MyModel() { Name = "test5" });
MyModels.Add(new MyModel() { Name = "test6" });
}
}
Step 3: please add the ItemsSource for your CarouselView and binding the properties for xamarin forms control(Label)
<CarouselView HorizontalOptions="Center" NumberOfSideItems="1" ItemsSource="{ Binding MyModels}">
<CarouselView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Frame HasShadow="True"
BorderColor="DarkGray"
CornerRadius="5"
Margin="20"
HeightRequest="300"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand">
<StackLayout>
<Label Text="{Binding Name}"
FontAttributes="Bold"
FontSize="Large"
HorizontalOptions="Center"
VerticalOptions="Center" />
</StackLayout>
</Frame>
</StackLayout>
</DataTemplate>
</CarouselView.ItemTemplate>
</CarouselView>
Step 4: backend code for your CarouselView.To bind your ModelView for layout.
BindingContext = new MyModelView();
Here is an example project. you can refer to it.
https://github.com/851265601/MyShellCarouselView

ListView Data Binding in Xamarin Forms without using GetDashboard button

On Login or Navigating to Dashboard Page, fetching data from API, I am using an extra button (Show Communities) to fetch my Fetch my Data. here is my code
<StackLayout BackgroundColor="#30af91" Padding="60" VerticalOptions="Center">
<Entry Text="{Binding Username}" Placeholder="Username"/>
<Entry Text="{Binding Password}" IsPassword="True" Placeholder="Password"/>
<Button Command="{Binding LoginCommand}" Text="Login" Clicked="Button_OnClicked"/>
</StackLayout>
Button_OnClicked only navigate to Dashboard page
private async void Button_OnClicked(object sender, EventArgs e)
{
await Navigation.PushModalAsync(new Dashboard());
}
LoginCommand in LoginViewModel
public ICommand LoginCommand
{
get
{
return new Command(async() =>
{
var accesstoken = await _apiServices.LoginAsync(Username, Password);
Settings.AccessToken = accesstoken;
});
}
}
Here is my Dashboard Page
<MasterDetailPage 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.Dashboard">
<MasterDetailPage.Master>
<ContentPage Title="Menu">
<ContentPage.BindingContext>
<viewModels:DashboardViewModel />
</ContentPage.BindingContext>
<ContentPage.Content>
<StackLayout>
<Button x:Name="BtnActiveForm" Text="Active Forms" Clicked="BtnActiveForm_OnClicked"></Button>
<Button x:Name="BtnCommunity" Text="My Communities" Clicked="BtnCommunity_OnClicked"></Button>
<Button x:Name="BtnHistory" Text="Sealed Forms" Clicked="BtnHistory_OnClicked"></Button>
<Button Text="Logout" Command="{Binding LogoutCommand}" Clicked="Logout_OnClicked"/>
</StackLayout>
</ContentPage.Content>
</ContentPage>
</MasterDetailPage.Master>
</MasterDetailPage>
Here is my Communities page where i am using an extra button using GetDashboard Command
<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>
<ContentPage.ToolbarItems>
<ToolbarItem Text="Add New"
Icon="add.png"
Priority="0"
Clicked="MenuItem_OnClicked"/>
</ContentPage.ToolbarItems>
<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.
every page has an OnAppearing method that fires when the page is display. You can use this to load your data instead of having the user click a button.
public override async void OnAppearing() {
base.OnAppearing();
var accessToken = Settings.AccessToken;
UserDashboard = await _apiServices.GetDashboard(accessToken);
}

Resources