Getting Started with Xamarin Chat (SfChat)

25 Sep 202320 minutes to read

Assembly deployment

After installing Essential Studio for Xamarin, you can find all the required assemblies in the installation folders, {Syncfusion Essential Studio Installed location} \Essential Studio\{Version #}\Xamarin\lib.

E.g.: C:\Program Files (x86) \Syncfusion\Essential Studio\19.1.0.54\Xamarin\lib

NOTE

Assemblies can be found in unzipped package location(Documents/Syncfusion/{Version #}/Xamarin/lib) in Mac.

NuGet configuration

To install the required NuGet for the SfChat control in the application, configure the NuGet packages of the Syncfusion components.

Refer to the following KB to configure the NuGet packages of the Syncfusion components:

How to configure package source and install Syncfusion NuGet packages in an existing project?

The following NuGet package should be installed to use the SfChat control in the application.

Project Required package
Xamarin.Forms Syncfusion.Xamarin.SfChat

Adding SfChat reference

You can add SfChat reference using one of the following methods:

Method 1: Adding SfChat reference from nuget.org

Syncfusion Xamarin components are available in nuget.org. To add SfChat to your project, open the NuGet package manager in Visual Studio, search for Syncfusion.Xamarin.SfChat, and then install it.

Adding Xamarin Chat reference from NuGet

NOTE

Install the same version of SfChat NuGet in all the projects.

Method 2: Adding SfChat reference from toolbox

Syncfusion also provides Xamarin Toolbox. Using this toolbox, you can drag the SfChat control to the XAML page. It will automatically install the required NuGet packages and add the namespace to the page. To install Syncfusion Xamarin Toolbox, refer to Toolbox.

Method 3: Adding SfChat assemblies manually from the installed location

If you prefer to manually reference the assemblies instead referencing from NuGet, add the following assemblies in respective projects.

Location: {Installed location}/{version}/Xamarin/lib

PCL Syncfusion.DataSource.Portable.dll
Syncfusion.GridCommon.Portable.dll
Syncfusion.Core.XForms.dll
Syncfusion.SfCalendar.XForms.dll
Syncfusion.Buttons.XForms.dll
Syncfusion.SfListView.XForms.dll
Syncfusion.SfChat.XForms.dll
Syncfusion.Licensing.dll
Android Syncfusion.DataSource.Portable.dll
Syncfusion.GridCommon.Portable.dll
Syncfusion.Core.XForms.dll
Syncfusion.Core.XForms.Android.dll
Syncfusion.SfCalendar.XForms.dll
Syncfusion.SfCalendar.XForms.Android.dll
Syncfusion.Buttons.XForms.dll
Syncfusion.Buttons.XForms.Android.dll
Syncfusion.SfListView.XForms.dll
Syncfusion.SfListView.XForms.Android.dll
Syncfusion.SfChat.XForms.dll
Syncfusion.SfChat.XForms.Android.dll
Syncfusion.Licensing.dll
iOS Syncfusion.DataSource.Portable.dll
Syncfusion.GridCommon.Portable.dll
Syncfusion.Core.XForms.dll
Syncfusion.Core.XForms.iOS.dll
Syncfusion.SfCalendar.XForms.dll
Syncfusion.SfCalendar.XForms.iOS.dll
Syncfusion.Buttons.XForms.dll
Syncfusion.Buttons.XForms.iOS.dll
Syncfusion.SfListView.XForms.dll
Syncfusion.SfListView.XForms.iOS.dll
Syncfusion.SfChat.XForms.dll
Syncfusion.SfChat.XForms.iOS.dll
Syncfusion.Licensing.dll
UWP Syncfusion.DataSource.Portable.dll
Syncfusion.GridCommon.Portable.dll
Syncfusion.Core.XForms.dll
Syncfusion.Core.XForms.UWP.dll
Syncfusion.SfInput.UWP.dll
Syncfusion.SfShared.UWP.dll
Syncfusion.SfCalendar.XForms.dll
Syncfusion.SfCalendar.XForms.UWP.dll
Syncfusion.Buttons.XForms.dll
Syncfusion.Buttons.XForms.UWP.dll
Syncfusion.SfListView.XForms.dll
Syncfusion.SfListView.XForms.UWP.dll
Syncfusion.SfChat.XForms.dll
Syncfusion.SfChat.XForms.UWP.dll
Syncfusion.Licensing.dll

NOTE

To know more about obtaining our components, refer to these links for Mac and Windows.

IMPORTANT

Starting with v16.2.0.x, if you reference Syncfusion assemblies from the trial setup or from the NuGet feed, you also have to include a license key in your projects. Please refer to Syncfusion license key to know about registering Syncfusion license key in your Xamarin application to use our components.

Launching the SfChat on each platform

To use the SfChat inside an application, each platform application must initialize the SfChat renderer. This initialization step varies from platform to platform and is discussed in the following sections:

Android

The Android launches the SfChat without any initialization and is enough to only initialize the Xamarin.Forms Framework to launch the application.

NOTE

If you are adding the references from toolbox, this step is not needed.

iOS

To launch the SfChat in iOS, call the SfChatRenderer.Init() in the FinishedLaunching overridden method of the AppDelegate class after the Xamarin.Forms Framework initialization and before the LoadApplication is called as demonstrated in the following code example:

  • C#
  • public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        
        global::Xamarin.Forms.Forms.Init ();
        Syncfusion.XForms.iOS.Chat.SfChatRenderer.Init();
        LoadApplication (new App ());
        
    }

    Universal Windows Platform (UWP)

    To launch the SfChat in UWP, call the SfChatRenderer.Init() in the MainPage constructor before the LoadApplication is called as demonstrated in the following code example.

  • C#
  • public MainPage()
    {
        
        Syncfusion.XForms.UWP.Chat.SfChatRenderer.Init();
        LoadApplication (new App ());
        
    }

    Release mode issue in UWP platform

    The known Framework issue in UWP platform is that the custom controls will not render when deployed the application in Release Mode. It can be resolved by initializing the SfChat assemblies in App.xaml.cs in UWP project as in the following code snippet.

  • C#
  • // In App.xaml.cs
    
    protected override void OnLaunched(LaunchActivatedEventArgs e)
    {
        
    
        rootFrame.NavigationFailed += OnNavigationFailed;
            
        // you should add `using System.Reflection;`
        List<Assembly> assembliesToInclude = new List<Assembly>();
    
        //Now, add all the assemblies your app uses
        assembliesToInclude.Add(typeof(SfButtonRenderer).GetTypeInfo().Assembly);
        assembliesToInclude.Add(typeof(SfBorderRenderer).GetTypeInfo().Assembly);
        assembliesToInclude.Add(typeof(SfCalendarRenderer).GetTypeInfo().Assembly);
        assembliesToInclude.Add(typeof(SfListViewRenderer).GetTypeInfo().Assembly);
        assembliesToInclude.Add(typeof(SfChatRenderer).GetTypeInfo().Assembly);
    
        // replaces Xamarin.Forms.Forms.Init(e);        
        Xamarin.Forms.Forms.Init(e, assembliesToInclude);
            
             
    }

    Create a simple SfChat

    This section explains how to create a SfChat and configure it. The SfChat control can be configured entirely in C# code or using XAML markup.

    NOTE

    You can download the complete project of this demo from GitHub.

    In this walk through, a new application can be created that contains the SfChat which includes the following topics:

    Creating the project

    Create a new BlankApp (Xamarin.Forms.Portable) application in Xamarin Studio or Visual Studio for Xamarin.Forms.

    Adding SfChat in Xamarin.Forms

    1. Add the required assembly references to the pcl and renderer projects as discussed in the Assembly deployment section.

    2. Import the SfChat control namespace as xmlns:sfChat="clr-namespace:Syncfusion.XForms.Chat;assembly=Syncfusion.SfChat.XForms" in XAML Page.

    3. Set the SfChat control as content to the ContentPage.

    <?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:GettingStarted;assembly=GettingStarted"
                 xmlns:sfChat="clr-namespace:Syncfusion.XForms.Chat;assembly=Syncfusion.SfChat.XForms"
                 x:Class="GettingStarted.MainPage">
    
        <ContentPage.Content>
            <sfChat:SfChat x:Name="sfChat" />
        </ContentPage.Content>
    </ContentPage>
    using Syncfusion.XForms.Chat;
    using Xamarin.Forms;
    
    namespace GettingStarted
    {
        using Syncfusion.XForms.Chat;
        using Xamarin.Forms;
    
        public partial class MainPage : ContentPage
        {
            public MainPage()
            {
                InitializeComponent();
                SfChat sfchat = new SfChat();
                this.Content = sfchat;
            }
        }
    }

    Creating the ViewModel for the SfChat

    The SfChat is a data-bound control displaying a collection of messages between users. Hence, messages should be created and binded to the control.

    Create a simple message collection as shown in the following code example in a new class file. Save it as GettingStartedViewModel.cs file:

  • C#
  • public class GettingStartedViewModel : INotifyPropertyChanged
        {
            /// <summary>
            /// Collection of messages in a conversation.
            /// </summary>
            private ObservableCollection<object> messages;
    
            /// <summary>
            /// Current user of chat.
            /// </summary>
            private Author currentUser;
    
            public GettingStartedViewModel()
            {
                this.messages = new ObservableCollection<object>();
                this.currentUser = new Author() { Name = "Nancy", Avatar = "Nancy.png" };
                this.GenerateMessages();
            }
    
            /// <summary>
            /// Gets or sets the collection of messages of a conversation.
            /// </summary>
            public ObservableCollection<object> Messages
            {
                get
                {
                    return this.messages;
                }
    
                set
                {
                    this.messages = value;
                }
            }
    
            /// <summary>
            /// Gets or sets the current user of the message.
            /// </summary>
            public Author CurrentUser
            {
                get
                {
                    return this.currentUser;
                }
                set
                {
                    this.currentUser = value;
                    RaisePropertyChanged("CurrentUser");
                }
            }
    
            /// <summary>
            /// Property changed handler.
            /// </summary>
            public event PropertyChangedEventHandler PropertyChanged;
    
            /// <summary>
            /// Occurs when property is changed.
            /// </summary>
            /// <param name="propName">changed property name</param>
            public void RaisePropertyChanged(string propName)
            {
                if (this.PropertyChanged != null)
                {
                    this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
                }
            }
    
            private void GenerateMessages()
            {
                this.messages.Add(new TextMessage()
                {
                    Author = currentUser,
                    Text = "Hi guys, good morning! I'm very delighted to share with you the news that our team is going to launch a new mobile application.",
                });
    
                this.messages.Add(new TextMessage()
                {
                    Author = new Author() { Name = "Andrea", Avatar = "Andrea.png" },
                    Text = "Oh! That's great.",
                });
    
                this.messages.Add(new TextMessage()
                {
                    Author = new Author() { Name = "Harrison", Avatar = "Harrison.png" },
                    Text = "That is good news.",
                });
    
                this.messages.Add(new TextMessage()
                {
                    Author = new Author() { Name = "Margaret", Avatar = "Margaret.png" },
                    Text = "What kind of application is it and when are we going to launch?",
                });
    
                this.messages.Add(new TextMessage()
                {
                    Author = currentUser,
                    Text = "A kind of Emergency Broadcast App.",
                });
            }
        }

    Binding Messages to SfChat

    To bind the messages to SfChat, set the SfChat.Messages property as follows. You can bind the message collection of the SfChat either from XAML or in code.

    The following code example binds the collection created in previous step to SfChat.Messages property.

    <?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:sfChat="clr-namespace:Syncfusion.XForms.Chat;assembly=Syncfusion.SfChat.XForms"
                 xmlns:local="clr-namespace:GettingStarted"
                 x:Class="GettingStarted.MainPage">
    
        <ContentPage.BindingContext>
            <local:GettingStartedViewModel/>
        </ContentPage.BindingContext>
        
        <ContentPage.Content>
                        <sfChat:SfChat x:Name="sfChat"
                               Messages="{Binding Messages}"
                               CurrentUser="{Binding CurrentUser}"
                               ShowOutgoingMessageAvatar="True" />
    	<ContentPage.Content>					   
    </ContentPage>
    using Syncfusion.XForms.Chat;
    using Xamarin.Forms;
    
    namespace GettingStarted
    {
        public partial class MainPage : ContentPage
        {
            SfChat sfChat;
            GettingStartedViewModel viewModel;
            public MainPage()
            {
                InitializeComponent();
                this.sfChat = new SfChat();
                this.viewModel = new GettingStartedViewModel();
                this.sfChat.Messages = viewModel.Messages;
                this.sfChat.CurrentUser = viewModel.CurrentUser;
                this.sfChat.ShowOutgoingMessageAvatar = true;
                this.Content = sfChat;
            }
        }
    }

    Run the application to render the following output.

    Xamarin Forms Chat

    Showing time break between messages

    Messages can be separated based on the date specified in the message and this can be achieved by setting the SfChat.ShowTimeBreak property to true. It can be done from both XAML and code. The following code example illustrates this:

    <?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:sfChat="clr-namespace:Syncfusion.XForms.Chat;assembly=Syncfusion.SfChat.XForms"
                 xmlns:local="clr-namespace:GettingStarted"
                 x:Class="GettingStarted.MainPage">
    
        <ContentPage.BindingContext>
            <local:GettingStartedViewModel/>
        </ContentPage.BindingContext>
        
           <ContentPage.Content>
            <sfChat:SfChat x:Name="sfChat"
                           Messages="{Binding Messages}"
                           ShowTimeBreak="True"
                           ShowIncomingMessageTimestamp="True"
                           ShowOutgoingMessageTimestamp="True"
                           IncomingMessageTimestampFormat="hh:mm tt"
                           OutgoingMessageTimestampFormat="hh:mm tt"
                           CurrentUser="{Binding CurrentUser}" />
        </ContentPage.Content>
    
    </ContentPage>
    using Syncfusion.XForms.Chat;
    using Xamarin.Forms;
    
    namespace GettingStarted
    {
        public partial class MainPage : ContentPage
        {
            SfChat sfChat;
            GettingStartedViewModel viewModel;
            public MainPage()
            {
                InitializeComponent();
                sfChat = new SfChat();
                viewModel = new GettingStartedViewModel();
                this.sfChat.Messages = viewModel.Messages;
                this.sfChat.IncomingMessageTimestampFormat = "hh:mm tt";
                this.sfChat.OutgoingMessageTimestampFormat = "hh:mm tt";
                this.sfChat.ShowIncomingMessageTimestamp = true;
                this.sfChat.ShowOutgoingMessageTimestamp = true;
                this.sfChat.ShowTimeBreak = true;
                this.sfChat.CurrentUser = viewModel.CurrentUser;
                this.Content = sfChat;
            }
        }
    }

    Run the application to render the following output.

    Xamarin Forms Chat time break mode

    See also

    How to connect Azure Bot Service to Xamarin.Forms Chat Control