Introduction
This article demonstrates how to create Message Center application using C# and XAML in Xamarin Forms.
Let’s start,
Step 1
Open Visual Studio and go to New Project >> Installed >> Visual C# >> Cross-Platform >> Cross Patform App (Xamarin).
Select Cross-Platform App, then give Project Name and Project Location.
Step 2
Next, open Solution Explorer >> Project Name >> MainPage.xaml. After that, open the Design View of this page.
Step 3
We need to add three buttons and different click events. Next, we are Binding Events Save to add Items Source in ListView.
XML Code
- <?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:Messagecenters"
- x:Class="Messagecenters.MainPage">
-
- <StackLayout Margin="0,20,0,0">
-
- <StackLayout Orientation="Horizontal"
- HorizontalOptions="CenterAndExpand">
- <Button Text="Sender"
- Clicked="HandleSender_Clicked" />
- <Button Text="Reciver"
- Clicked="HandleReceiver_Clicked" />
- <Button Text="Clear"
- Clicked="HandleClear_Clicked" />
- </StackLayout>
-
- <ListView ItemsSource="{Binding Events}" />
-
- </StackLayout>
-
- </ContentPage>
-
Step 4
Next Open Solution Explorer, Project Name, MainPage.xaml.cs and then click to Open C# Code.
C# Code
- using System;
- using System.Collections.ObjectModel;
- using Xamarin.Forms;
-
- namespace Messagecenters
- { public partial class MainPage : ContentPage
- {
- private string _tickContract = "tick";
- public ObservableCollection<string> Events { get; set; } = new ObservableCollection<string>();
- public MainPage()
- {
- InitializeComponent(); BindingContext = this;
- }
- void HandleSender_Clicked(object sender, System.EventArgs e)
- {
- MessagingCenter.Send(this, _tickContract, DateTime.Now);
- }
- void HandleReceiver_Clicked(object sender, EventArgs args)
- {
- MessagingCenter.Subscribe<MainPage, DateTime>(this, _tickContract, (s, a) => {
- Events.Add($"Received message at {a.ToString()}");
- });
- }
- void HandleClear_Clicked(object sender, EventArgs args)
- {
- Events.Clear();
- }
- }
- }
Here, first we add namespace and then declare variable of String, after that value store using this variable, Go to on create () Observable Collection of given datatype. Then adding button events and some different conditions.
Create Receiver handle click Events: Events.Add($"Received message at {a.ToString()}");
Step 5
Go to right click on solution explorer, Set StartUp Project, after that open Solution Project name Property pages. Select Multiple Startup projects, Start with Android and UWP platforms.
Step 6
Press F5 OR Build and Run the application, after that open Application Click Receiver button
And then click Sender button
OUTPIUT 1
OUTPUT 2
Again continue same process, after that see the output adding two values on one ListView.
OUTPUT 3
Finally, we have successfully created a Xamarin Forms Message Center App.