loading...
Cover image for Load More Messages, Attach and Send Images and Media, Show Interactive Cards in Xamarin Chat Control
Syncfusion, Inc.

Load More Messages, Attach and Send Images and Media, Show Interactive Cards in Xamarin Chat Control

sureshmohan profile image Suresh Mohan Originally published at syncfusion.com on ・6 min read

Ever since the Xamarin Chat control was launched back in January, we’ve been getting overwhelming feedback requesting new features, behaviors, and capabilities. We have listened. Understanding the evolving needs of a conversational UI in modern applications, we in the development team put the pedal to the metal and made sure each of your requests was fulfilled.

We are thrilled to announce that, with the release of Essential Studio 2020 Volume 2, our Xamarin Chat control is now more powerful, thanks to the inclusion of the following features:

Let’s talk about them with code examples!

Load more messages on demand

You can now scroll to the top of the message list to fetch the old messages on demand in runtime. This can be done either automatically or manually (by tapping the load more button).

You can also apply a custom template to the load more button and a loading indicator if you wish.

Refer to the following code example.

<sfChat:SfChat x:Name="sfChat"
    LoadMoreCommand="{Binding LoadMoreCommand}"
    LoadMoreBehavior="{Binding LoadMoreBehavior}"
    Messages="{Binding Messages}"
    CurrentUser="{Binding CurrentUser}" >
</sfChat:SfChat>

ViewModel.cs

public partial class LoadMoreViewModel : INotifyPropertyChanged
{
    private LoadMoreOption loadMoreBehavior = LoadMoreOption.Auto;

    /// <summary>
    /// Gets or sets the load more command of SfChat.
    /// </summary>
    public ICommand LoadMoreCommand { get; set; }

    /// <summary>
    /// Gets or sets the load more behavior of the chat control.
    /// </summary>
    public bool LoadMoreBehavior
    {
        get { return this.loadMoreBehavior; }
        set { this.loadMoreBehavior = value; }
    }

    /// <summary>
    /// Gets or sets the message conversation of SfChat.
    /// </summary>
    public ObservableCollection<object> Messages
    {
        get { return this.messages; }
        set { this.messages = value; }
    }

    public LoadMoreViewModel()
    {
        this.Messages = CreateMessages();
        LoadMoreCommand = new Command<object>(LoadMoreItems, CanLoadMoreItems);
    }

    /// <summary>
    /// Returns whether the load more command can execute.
    /// </summary>        
    private bool CanLoadMoreItems(object obj)
    {
        // If messages are still there in the old message collection, then execute the load more command.
        if (this.OldMessages.Count > 0)
        {
            return true;
        }
        else
        {
            // Set the load more behavior of chat to none from auto to cancel the load more operation.
            this.LoadMoreBehavior = LoadMoreOption.None;
            return false;
        }
    }

    /// <summary>
    /// Action raised when the load more command is executed.
    /// </summary>
    private async void LoadMoreItems(object obj)
    {
        try
        {
            await Task.Delay(3000);
            LoadMoreMessages();
        }
    }

    /// <summary>
    /// Adds the next ten messages from the older messages of the conversation to <see cref="SfChat"/>'s message collection.
    /// </summary>
    /// <param name="index">index of message collection.</param>
    /// <param name="count">count of the messages to be added.</param>
    private void LoadMoreMessages()
    {
        for (int i = 1; i <= 10; i++)
        {
            var oldMessage = this.OldMessages[this.OldMessages.Count - 1];
            this.Messages.Insert(0, oldMessage);
            this.OldMessages.Remove(oldMessage);
        }
    }
}

Load more messages on demand
Load more messages on demand

Sticky keyboard

One customer commented, “Hi! In a great chat control the keyboard should stay focused until the user actively dismisses it using tap outside or swipe to dismiss.”

We agreed. We’ve provided support to keep the keyboard open in the view, even after a message is sent or focus is lost, just like in most mainstream chat applications.

Refer to the following code example.

this.sfChat.ShowKeyboardAlways = true;

Card messages

With this new message type, you can now show a list of interactive cards to tie in with the cards of popular bot frameworks with:

  • Images
  • Buttons
  • Text (title, subtitle, and description)

Refer to the following code example.

private void GenerateCardMessages()
{
    CardMessage cardMessage = new CardMessage();
    cardMessage.Author = new Author() { Name = "Andrea", Avatar = "People_Circle2.png" };

    ObservableCollection<Card> cards = new ObservableCollection<Card>();

    Card card1 = new Card();
    card1.Title = "Subscriptions";
    card1.Image = ImageSource.FromResource("Clock.png");
    card1.Description = "Send me news daily /n Send me poems daily";

    Card card2 = new Card();
    card2.Title = "Weather";
    card2.Image = ImageSource.FromResource("Sun.png");
    card2.Description = "What's the weather? /n What’s the weather in Miami?";

    cards.Add(card1);
    cards.Add(card2);
    cardMessage.Cards = cards;
    this.Messages.Add(cardMessage);
}

Card messages in Xamarin chat
Card messages in Xamarin chat

Template support for messages

You can customize the message views as you wish with support to load templates for each message. You can also load custom templates based on the message type, text, author, and so on. The possibilities are endless.

Refer to the following code example.

this.sfChat.MessageTemplate = new MyCustomMessageTemplateSelector();

public class MyCustomMessageTemplateSelector : ChatMessageTemplateSelector
{
    private readonly DataTemplate ratingDataTemplate;
    public MyCustomMessageTemplateSelector(SfChat chat) : base(chat)
    {
        this.ratingDataTemplate = new DataTemplate(typeof(RatingTemplate));
    }

    protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
    {
        if (item as ITextMessage != null && item as ITextMessage.Text == "How would you rate your interaction with our travel bot?")
        {
            // returns a custom rating template for this message.
            return this.ratingDataTemplate;
        }
        else
        {
            // returns default template for all other messages.
            return base.OnSelectTemplate(item, container);
        }
    }
}

Template support for messages in Xamarin Chat
Template support for messages in Xamarin Chat

Restricting multi-line input in editor (single-line messages)

You can now:

  • Restrict multi-line input from the users.
  • Show a send button in the keyboard.

Users can no longer insert a new line in messages when the SfChat.AllowMultilineInput property is set to false.

Image messages

Sharing images as part of conversations is now easier with this new image message type. Users can now easily send and receive images. This message type has built-in command support to trigger actions when an image is tapped. You can check this UG documentation for more real-time examples and code examples.

Refer to the following code example.

private void AddImageMessage(object obj)
{
    this.Messages.Add(new ImageMessage()
    {
        Text = "Say hi to Ceasar!",
        Source = ImageSource.FromResource("Caesar.png"),
        Author = new Author() { Name = "Andrea", Avatar = ImageSource.FromResource("Andrea.png")},
    });

    this.Messages.Add(new ImageMessage()
    {
        Text = "hi from Bolt!",
        Source = ImageSource.FromResource("Bolt.png"),
        Author = new Author() { Name = "Michael", Avatar = ImageSource.FromResource("Michael.png") },
    });
}

Image messages in Xamarin Chat
Image messages in Xamarin Chat

Media attachment button

You can now show a built-in media attachment button beside the send message icon at the bottom of the Chat control. It allows the users to load media like images, GIF images, documents, and more as messages in the chat.

With its template support and auto sizing capabilities, you can also load views that contain more than one button. You can check this UG documentation for more real-time examples.

Media attachment button in Xamarin Chat
Media attachment button in Xamarin Chat

Scrolled event

Now you can get notifications whenever you scroll a chat conversation with the information that the chat has reached the bottom or top of the message list.

Refer to the following code example.

this.sfChat.Scrolled += ChatScrolled;

private void ChatScrolled(object sender, ChatScrolledEventArgs e)
{
    sfChat.CanAutoScrollToBottom = e.IsBottomReached;
    if (e.IsBottomReached || e.IsTopReached)
    {
        DisplayAlert(Alert, End of conversation reached…”, OK);
    }
}

Conclusion

In this blog post, we glanced at the new features included in the Xamarin Chat control in the 2020 Volume 2 release. In addition to these features, we have also included minor features: auto scrolling to the bottom when new messages are added, notifications when typing starts or ends, hyperlink messages as outgoing messages, and so on. Check out the full release notes for more details.

We hope that you like and play around with these new features in our Chat control. Let us know in the comments section what you think of these new features and what other features you expect from the Chat control in the future. As always, we are listening.

You can also contact us through our support forum, Direct-Trac, or feedback portal. We will be happy to assist you.

Posted on by:

sureshmohan profile

Suresh Mohan

@sureshmohan

Suresh is a Product Manager at Syncfusion and a technology enthusiast. He helps people follow best practices in coding and in using Syncfusion controls in their applications.

Syncfusion, Inc.

Syncfusion provides third-party UI components for React, Vue, Angular, JavaScript, Blazor, ASP.NET Web Forms, MVC, Core, WinForms, WPF, UWP and Xamarin.

Discussion

markdown guide