Xamarin Forms Button pass CommandParameter

  • by
xamarin-forms-button-pass-command-parameter-003

Xamarin forms How to pass CommandParameter on Button click:

Using CommandParameter we can bind multiple objects on our Xamarin application form to a single function and differentiate to perform a specific tasks. In the previous post we saw How to CRUD operations in SQLite database in Xamarin forms application. Here we will see how to pass commandParameter on a button click function.
 
DOWNLOAD SOURCE CODE
 
The example has two buttons, each with different parameters passed on its click event.

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:XamSample"
x:Class="XamSample.MainPage">

<StackLayout Orientation="Vertical" Padding="5">
<!-- Place new controls here -->
<Label Text="Xamarin Forms Command Parameter Sample"
HorizontalOptions="Center"
VerticalOptions="Start" Margin="5" />

<Button x:Name="btnOne" Text="Xamarin Forms" CommandParameter="Xamarin Forms"
Clicked="Button_Clicked" Margin="5"/>

<Button x:Name="btnTwo" Text="Node.js" CommandParameter="Node.js"
Clicked="Button_Clicked" Margin="5"/>
</StackLayout>

</ContentPage>

As you can see, btnOne passes the Xamarin Forms commandParameter and btnTwo passes Node.js parameter. They both are calling the same function.

MainPage.xaml.cs:

using System;
using Xamarin.Forms;

namespace XamSample
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}

private async void Button_Clicked(object sender, EventArgs e)
{
try
{
Button button1 = (Button)sender;
string commandParameter = button1.CommandParameter.ToString();
await DisplayAlert("Info", "You selected " + commandParameter, "Ok");
}
catch(Exception ex)
{
await DisplayAlert("Error occurred", ex.Message.ToString(), "Ok");
}
}
}
}

Now when we click on the buttons, Button_Clicked function will be called. This method will parse the CommandParameter passed and display it on Pop-Up box (DisplayAlert).

xamarin-forms-button-pass-command-parameter-003

 

DOWNLOAD SOURCE CODE

Also see:
Xamarin forms SQLite DB – Perform CRUD operation.

Xamarin forms SkiaSharp – Creating different shapes

Xamarin forms Creating SQLite Database

Xamarin forms Creating Custom Button control

 


  1. Base64Encode.io - Realtime Encode your string to Base64 format.
  2. Base64Decode.io - Realtime Decode Base64 data to plain text.
  3. Md5Hash.io - Realtime Encoding in Md5Hash.