How to bind DatePicker and Picker in Xamarin - xamarin

I am trying to register a user on my application using web API on Xamarin.
Here is registration form in RegisterPage.xaml
<Entry Text="{Binding FirstName}" Placeholder="First Name"/>
<Entry Text="{Binding LastName}" Placeholder="Last Name"/>
<Entry Text="{Binding UserName}" Placeholder="Username"/>
<Entry Text="{Binding Email}" Placeholder="Email" />
<Entry Text="{Binding Password}" Placeholder="Password" IsPassword="True"/>
<Entry Text="{Binding ConfirmPassword}" Placeholder="Confirm Password" IsPassword="True"/>
<DatePicker x:Name="BirthDay" MinimumDate="1/1/1948" MaximumDate="12/31/2007"/>
<Label Text="Gender"/>
<Picker x:Name="GenderPicker" SelectedIndexChanged="GenderPicker_OnSelectedIndexChanged"/>
<Label Text="User Role"/>
<Picker x:Name="RolePicker" SelectedIndexChanged="RolePicker_OnSelectedIndexChanged"/>
<Button Command="{Binding RegisterCommand}" Text="Register"/>
<Label Text="{Binding Message}" />
Here is my RegisterPage.xaml.cs file
public partial class RegisterPage : ContentPage
{
public RegisterPage()
{
InitializeComponent();
GenderPicker.Items.Add("Male");
GenderPicker.Items.Add("Female");
RolePicker.Items.Add("Admin");
RolePicker.Items.Add("Participant");
}
private void GenderPicker_OnSelectedIndexChanged(object sender, EventArgs e)
{
var gender = GenderPicker.Items[GenderPicker.SelectedIndex];
}
private void RolePicker_OnSelectedIndexChanged(object sender, EventArgs e)
{
var role = RolePicker.Items[RolePicker.SelectedIndex];
}
}
On submitting the registration form I am not receiving my values against DatePiker and Picker into the RegisterCommand
Here is my RegisterCommand , I am receiving other attributes but not from DatePiker and Picker
public ICommand RegisterCommand
{
get
{
return new Command(async () =>
{
var isSuccess = await _apiServices.RegisterAsync(FirstName,LastName,UserName,Email,Password,ConfirmPassword,BirthDate,Gender,UserRole);
Message = isSuccess ? "Registered Successfully" : "Retry Later";
});
}
}

Starting in Xamarin Forms 2.3.4 thy finally introduced Binding to the Picker. You only need to bind to the SelectedItem as shown below.
<?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:local="clr-namespace:PickerDemo"
x:Class="PickerDemo.PickerDemoPage">
<ContentPage.BindingContext>
<local:PickerDemoPageViewModel />
</ContentPage.BindingContext>
<StackLayout Padding="10,20">
<!-- Picker with explicitly set values in XAML -->
<Picker SelectedItem="{Binding SelectedItem}">
<Picker.Items>
<x:String>Item 1</x:String>
<x:String>Item 2</x:String>
</Picker.Items>
</Picker>
<Label Text="{Binding SelectedItem,StringFormat='You Selected: {0}'}" />
<!-- Picker with Dynamically set values -->
<Picker ItemsSource="{Binding SomeCollection}" SelectedItem="{Binding AnotherItem}" />
<Label Text="{Binding AnotherItem,StringFormat='You picked: {0}'}" />
<!-- Date Picker using a custom display format -->
<DatePicker Date="{Binding SomeDate}" Format="MMMM dd, yyyy" />
<Label Text="{Binding SomeDate,StringFormat='{0:dd MMMM, yyyy}'}" />
</StackLayout>
</ContentPage>

Related

LongPress is triggers while using PinchGestureRecognizer in xamarin forms

I am using xamarin community toolkit for LongPress and GestureRecognizers for PinchGestureRecognizer. After the completion of PinchGestureRecognizer, xct:TouchEffect.LongPressCommand is also fired. Is there any way to trigger these events once at a time?
Here is my code sample
<StackLayout
xct:TouchEffect.LongPressCommand="{Binding LongPressCommand}"
xct:TouchEffect.LongPressCommandParameter="LongPress"
BackgroundColor="Red">
<Frame
Padding="24"
BackgroundColor="#2196F3"
CornerRadius="0">
<Label
FontSize="36"
HorizontalTextAlignment="Center"
Text="Welcome to Xamarin.Forms!"
TextColor="White" />
</Frame>
<Label
Padding="30,10,30,10"
FontSize="Title"
Text="Start developing now" />
<Label
Padding="30,0,30,0"
FontSize="16"
Text="Make changes to your XAML file and save to see your UI update in the running app with XAML Hot Reload. Give it a try!" />
<Label Padding="30,24,30,0" FontSize="16">
<Label.FormattedText>
<FormattedString>
<FormattedString.Spans>
<Span Text="Learn more at " />
<Span FontAttributes="Bold" Text="https://aka.ms/xamarin-quickstart" />
</FormattedString.Spans>
</FormattedString>
</Label.FormattedText>
</Label>
<StackLayout.GestureRecognizers>
<PinchGestureRecognizer PinchUpdated="OnPinchUpdated" />
</StackLayout.GestureRecognizers>
</StackLayout>
The cs file
public ICommand LongPressCommand { get; set; }
public MainPage()
{
InitializeComponent();
LongPressCommand = new Command<string>(LongPress);
BindingContext = this;
}
public void LongPress(string flag)
{
}
private void OnPinchUpdated(object sender, PinchGestureUpdatedEventArgs e)
{
}
}
You can set a duration of the LongPress command to trigger the command. The default is 500ms, you can set it via LongPressDuration property. In the example below, I set it to 3s which means the LongPress will be triggered after 3s . You can set the proper duration to avoid the conflict with PinchGestureRecognizer.
xct:TouchEffect.LongPressDuration="3000"

Prism and Control Templates

I'm trying to rewrite the sample "SimpleThemeWithTemplateBinding" that uses ControlTemplates, with Prism.
I also added a simple
HeaderText = "changed";
in the button to change the HeaderText in the ControlTemplate, and it works, in the original sample.
So I copied the template in my app.xaml:
<ControlTemplate x:Key="TealTemplate">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="0.1*" />
<RowDefinition Height="0.8*" />
<RowDefinition Height="0.1*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.05*" />
<ColumnDefinition Width="0.95*" />
</Grid.ColumnDefinitions>
<BoxView Grid.ColumnSpan="2" Color="Teal" />
<Label Grid.Column="1" Text="{TemplateBinding BindingContext.HeaderText}" TextColor="White" VerticalOptions="Center" />
<ContentPresenter Grid.Row="1" Grid.ColumnSpan="2" />
<BoxView Grid.Row="2" Grid.ColumnSpan="2" Color="Teal" />
<Label Grid.Row="2" Grid.Column="1" Text="(c) Xamarin 2016" TextColor="White" VerticalOptions="Center" />
</Grid>
</ControlTemplate>
and just changed
{TemplateBinding HeaderText}
to
{TemplateBinding BindingContext.HeaderText}
VIEW:
<?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:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
prism:ViewModelLocator.AutowireViewModel="True"
x:Class="TestAppNSPrism7.Views.PrismContentPage9">
<ContentPage.Content>
<ContentView x:Name="contentView" Padding="0,0,0,0" ControlTemplate="{StaticResource TealTemplate}" >
<StackLayout>
<Label Text="Welcome to Xamarin.Forms! page1"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand" />
<Label Text="Buazz"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand" />
<Button Command="{Binding ButtonChangeValueCommand}" Text="Change value" ></Button>
</StackLayout>
</ContentView>
</ContentPage.Content>
</ContentPage>
VIEWMODEL:
public class PrismContentPage9ViewModel : ViewModelBase
{
ControlTemplate tealTemplate;
private string _headerText = "test";
public string HeaderText
{
get
{
return _headerText;
}
set { SetProperty(ref _headerText, value); }
}
public PrismContentPage9ViewModel(INavigationService navigationService) : base(navigationService)
{
tealTemplate = (ControlTemplate)Application.Current.Resources["TealTemplate"];
}
private DelegateCommand _buttonChangeValueCommand;
public DelegateCommand ButtonChangeValueCommand =>
_buttonChangeValueCommand ?? (_buttonChangeValueCommand = new DelegateCommand(ExecuteButtonChangeValueCommand));
void ExecuteButtonChangeValueCommand()
{
HeaderText = "changed";
}
}
The Page gets loaded correctly, with the ControlTemplate, and the HeaderText is "test".
So it seems the HeaderText binding with the ControlTemplate is working.
But when I set the HeaderText to "changed", the Label doesn't get updated.
I debugged and checked that once I press the button it goes through ExecuteButtonChangeValueCommand() and SetProperty(ref _headerText, value)
Any suggestion?
Thanks!
I changed the TemplateBinding from :
Text="{TemplateBinding BindingContext.HeaderText}"
to:
Text="{TemplateBinding Parent.BindingContext.HeaderText}"
and it updates now when I press your changed button.
I believe its due to the template not having a binding context automatically set but the template's parent (PrismContentPage9) has its BindingContext auto-wired from Prism's AutowireViewModel property, e.g.,
prism:ViewModelLocator.AutowireViewModel="True"
Let me know if that works for you.

Xamarin Forms No property, bindable property, or event found for 'Sku', or mismatching type between value and property

In my xamarin project I have a custom button controller:
[XamlCompilation(XamlCompilationOptions.Compile)]
public class AddToCartButton : Button
{
public static readonly BindableProperty SkuPoperty = BindableProperty.Create(nameof(Sku), typeof(ApiModels.SkuDetailModel), typeof(AddToCartButton));
public ApiModels.SkuDetailModel Sku
{
get { return (ApiModels.SkuDetailModel)GetValue(SkuPoperty); }
set { SetValue(SkuPoperty, value); }
}
public AddToCartButton()
{
this.Clicked += AddToCartButton_Clicked;
}
public AddToCartButton(ApiModels.SkuDetailModel sku)
{
this.Sku = sku;
this.Clicked += AddToCartButton_Clicked;
}
private async void AddToCartButton_Clicked(object sender, EventArgs e)
{
var response = await Helpers.ApiHelper.CurrentAccess.AddToCart(new List<ApiModels.CartItem>() {
new ApiModels.CartItem() {
ItemCode = Sku.ItemCode,
Quantity = 1
}
});
// handle add modal
}
}
This is the exact same way I've created BindableProperties for ContentViews and what have you.
In my xaml referencing this controller, I have:
<local:AddToCartButton Text="Add to Cart" Style="{ DynamicResource SkuAddToCart }" Sku="{Binding Sku}" />
This line is causing my builds to fail, with the error:
Severity Code Description Project File Line Suppression State
Error Position 44:44. No property, bindable property, or event found for 'Sku', or mismatching type between value and property....
I can't seem to figure out why I'm getting it. All my types are consistent. The object I'm trying to bind is done like this:
public partial class SkuView : ContentView
{
public ApiModels.SkuDetailModel Sku { get; set; }
public SkuView(ApiModels.SkuDetailModel sku, string baseUrl, ApiModels.SimpleUser user)
{
BindingContext = this;
Sku = sku;
InitializeComponent();
Per request for xaml headers, here is the entire xaml file.
<?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:local="clr-namespace:myApp.Controls"
x:Class="myApp.Views.Products.SkuView">
<ContentView.Content>
<StackLayout>
<Grid Style="{ DynamicResource SkuGrid }">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="50" />
</Grid.RowDefinitions>
<StackLayout x:Name="ImageCell" Grid.Row="0" Grid.Column="0"></StackLayout>
<StackLayout x:Name="ContentCell" Grid.Row="0" Grid.Column="1">
<Label x:Name="DescriptionLabel" Style="{ DynamicResource SkuDescLabel }" />
<Label x:Name="ItemCodeLabel" Style="{ DynamicResource SkuItemCode }" />
<StackLayout x:Name="PricingLayout">
<!--<StackLayout Orientation="Horizontal">
<Label x:Name="PriceLabel" Style="{ DynamicResource SkuPricing }" />
<Label x:Name="PurchaseMultipleLabel" Style="{ DynamicResource SkuUom }" />
</StackLayout>-->
</StackLayout>
</StackLayout>
<StackLayout Orientation="Horizontal" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2">
<StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand">
<Button Text=" - " Style="{ DynamicResource SkuQtyStepper }" />
<Grid Margin="-10, 0">
<BoxView Color="DarkGray" Opacity=".6" Margin="0, 5"/>
<BoxView Color="White" Margin="2, 7"/>
<local:BorderlessEntry Style="{ DynamicResource SkuQtyEntry }" Keyboard="Numeric" Margin="2" HorizontalTextAlignment="Center" />
</Grid>
<Button Text=" + " Style="{ DynamicResource SkuQtyStepper }" />
</StackLayout>
<!--<StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand">
<Button Text=" - " Style="{ DynamicResource SkuQtyStepper }" />
<local:BorderedEntry Style="{ DynamicResource SkuQtyEntry }" Keyboard="Numeric" HeightRequest="20" />
<Button Text=" + " Style="{ DynamicResource SkuQtyStepper }" />
</StackLayout>-->
<local:AddToCartButton Text="Add to Cart" Style="{ DynamicResource SkuAddToCart }" Sku="{Binding Sku}" />
<!--<Button Text="Add to Cart" Style="{ DynamicResource SkuAddToCart }" />-->
</StackLayout>
</Grid>
<Grid HeightRequest="1" Style="{ DynamicResource BackgroundMediumGray }" />
</StackLayout>
</ContentView.Content>
In the property name, you have a typo:
public static readonly BindableProperty SkuPoperty = BindableProperty.Create(nameof(Sku), typeof(ApiModels.SkuDetailModel), typeof(AddToCartButton));
SkuPoperty => SkuProperty
Edit:
To elaborate, Xamarin requires to have PropertyNameProperty naming convention:
Creating a bindable property

Serialize Class Xamarin.Forms

I’m trying to serialize class but I can’t do it.
I have a class below:
public class DadosTitulo
{
public string nome { get; set; }
public string numeroCpfCnpj { get; set; }
public string logradouro { get; set; }
public string numero { get; set; }
public string complemento { get; set; }
public string bairro { get; set; }
public string cep { get; set; }
public string municipio { get; set; }
public string uf { get; set; }
public double valor { get; set; }
public string numeroDocumento { get; set; }
public string dataVencimento { get; set; }
public string celularDestino { get; set; }
public bool registroProducao { get; set; }
}
And in my MainPage.xaml.cs I have:
private async void btnAdicionar_Clicked(object sender, EventArgs e)
{
var retorno = "";
var titulo = new DadosTitulo
{
nome = txtNome.Text,
numeroCpfCnpj = txtNumeroCpfCnpj.Text,
logradouro = txtLogradouro.Text,
numero = txtNumero.Text,
complemento = txtComplemento.Text,
bairro = txtBairro.Text,
cep = txtCep.Text,
municipio = txtMunicipio.Text,
uf = txtUF.Text,
valor = Convert.ToDouble(txtValor.Text),
numeroDocumento = txtNumeroDocumento.Text,
dataVencimento = DataVencimento.Date.ToString("dd/MM/yyyy"),
celularDestino = txtDddCelularDestino.Text + txtNumCelularDestino.Text,
registroProducao = RegistraProducao
};
var registroService = new RegistroBoletoService();
retorno = registroService.RegistrarBoleto(titulo);
await DisplayAlert("Json", retorno, "OK");
}
Property Values from MainPage.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:local="clr-namespace:AppRegistraBoletoXF"
x:Class="AppRegistraBoletoXF.MainPage">
<StackLayout Orientation="Vertical">
<StackLayout>
<Label Text="Registra Boleto" TextColor="Indigo" FontSize="Medium" />
</StackLayout>
<StackLayout>
<Label Text="Informe os dados do Título:" TextColor="Black" FontSize="Small" />
</StackLayout>
<StackLayout>
<Entry x:Name="txtNome" Placeholder="Nome" HorizontalOptions="Start"
VerticalOptions="StartAndExpand" HeightRequest="35" WidthRequest="300" FontSize="Small"/>
<Entry x:Name="txtNumeroCpfCnpj" Placeholder="CPF/CNPJ" HorizontalOptions="Start"
VerticalOptions="StartAndExpand" HeightRequest="35" WidthRequest="300" FontSize="Small" />
<StackLayout Orientation="Horizontal">
<Entry x:Name="txtLogradouro" Placeholder="Logradouro" HorizontalOptions="StartAndExpand" VerticalOptions="Start"
HeightRequest="35" WidthRequest="160" FontSize="Small" />
<Entry x:Name="txtNumero" Placeholder="Número" HorizontalOptions="StartAndExpand" VerticalOptions="Start"
HeightRequest="35" WidthRequest="50" FontSize="Small" />
<Entry x:Name="txtComplemento" Placeholder="Complemento" HorizontalOptions="StartAndExpand" VerticalOptions="Start"
HeightRequest="35" WidthRequest="90" FontSize="Small" />
</StackLayout>
<StackLayout Orientation="Horizontal">
<Entry x:Name="txtBairro" Placeholder="Bairro" HorizontalOptions="StartAndExpand" VerticalOptions="Start"
HeightRequest="35" WidthRequest="180" FontSize="Small" />
<Entry x:Name="txtCep" Placeholder="CEP" HorizontalOptions="StartAndExpand" VerticalOptions="Start"
HeightRequest="35" WidthRequest="120" FontSize="Small" />
</StackLayout>
<StackLayout Orientation="Horizontal">
<Entry x:Name="txtMunicipio" Placeholder="Município" HorizontalOptions="StartAndExpand" VerticalOptions="Start"
HeightRequest="35" WidthRequest="250" FontSize="Small" />
<Entry x:Name="txtUF" Placeholder="UF" HorizontalOptions="StartAndExpand" VerticalOptions="Start"
HeightRequest="35" WidthRequest="50" FontSize="Small" />
</StackLayout>
<StackLayout Orientation="Horizontal">
<Entry x:Name="txtDddCelularDestino" Placeholder="DDD" HorizontalOptions="StartAndExpand" VerticalOptions="Start"
HeightRequest="35" WidthRequest="50" FontSize="Small" />
<Entry x:Name="txtNumCelularDestino" Placeholder="Celular Destino" HorizontalOptions="StartAndExpand" VerticalOptions="Start"
HeightRequest="35" WidthRequest="250" FontSize="Small" />
</StackLayout>
<Entry x:Name="txtNumeroDocumento" Placeholder="Número do Título" HorizontalOptions="Start"
VerticalOptions="StartAndExpand" HeightRequest="35" WidthRequest="300" FontSize="Small"/>
<Entry x:Name="txtValor" Placeholder="Valor do Título" HorizontalOptions="Start"
VerticalOptions="StartAndExpand" HeightRequest="35" WidthRequest="300" FontSize="Small"/>
<StackLayout Orientation="Horizontal">
<Label Text="Registro em Produção: " TextColor="Black" FontSize="Small" HorizontalOptions="Start"
VerticalOptions="StartAndExpand" />
<DatePicker DateSelected="DataSelecionada" HorizontalOptions="Start" VerticalOptions="StartAndExpand">
<DatePicker.Format>dd/MM/yyyy</DatePicker.Format>
</DatePicker>
</StackLayout>
<StackLayout Orientation="Horizontal">
<Label Text="Registro em Produção: " TextColor="Black" FontSize="Small" HorizontalOptions="Center"
VerticalOptions="StartAndExpand" />
<Switch IsToggled="False" Toggled="RegistrarProducao" HorizontalOptions="Center"
VerticalOptions="StartAndExpand" />
</StackLayout>
<Button HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand" HeightRequest="40" Text="Registrar Título"
Clicked="btnAdicionar_Clicked" FontSize="Small"/>
</StackLayout>
</StackLayout>
</ContentPage>
In RegistroBoletoService:
public string RegistrarBoleto(DadosTitulo dadosTitulo)
{
var data = JsonConvert.SerializeObject(dadosTitulo);
return data;
}
data allways return “{}”:
I have made a test calling RegistroBoletoService from Console Project, in the same Solution, and the result was as expected: data contains json
The interesting point that I noticed: when I have instantiated the class in MainPage.xaml.cs the behavior was diferent from Console Project, with Non-Public Members in the class:
Console Instantiate:
I think that this is the problem, anyone have an idea what is it happening ? Why when I have instantiated the class in the MainPage I get different behavior from the Console ?
Thanks a lot and sorry my English.
PS.: Project in .NET Standard; I’m not using MVVM in this case; I tried testing with the linker SDK Assemblies Only and None.

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