Is it possible to change message bubble background based on the sender?

I am using the SfChat control in a .Net MAUI 9.0 project and would like to change the background of the Message bubble to be the Color of the associated sender.  I am developing in Visual Studio using c# and XAML. Is this possible?


1 Reply

MM Muthukumar Madasamy Syncfusion Team April 11, 2025 01:56 PM UTC

Hi Chris,
To change the background color based on the sender, you can use a DataTemplateSelector along with custom templates for incoming and outgoing messages.
this.sfChat.MessageTemplate = new ChatMessageTemplateSelectorExt(this.sfChat);

// Template selector
 protected override DataTemplate? OnSelectTemplate(object item, BindableObject container)
 {
     var message = item as IMessage;
     if (message == null || Chat == null)
     {
         return null;
     }
     if (message.Author == Chat!.CurrentUser)
     {
         return outgoingDataTemplate;
     }
     else
     {
         return inComingDataTemplate;
     }
 }


A color converter can be applied to dynamically adjust the background color based on the author's name.

 public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
 {
     if (value != null)
     {
         if (value is "Antony")
         {
             return Colors.ForestGreen;
         }
         else if (value is "Nancy")
         {
             return Colors.LightGreen;
         }
         else
         {
             return Colors.DodgerBlue;
         }
     }
     return Colors.DimGrey;
 }


In both message templates, bind the background property to the author's name using the color converter.

             Spacing="4"
             Padding="16,8,16,8"
             Background="{Binding Author.Name, Converter = {StaticResource authorBackugroundColorConvertor}}">
            
                   Text="{Binding Text}"
                   LineBreakMode="WordWrap"
                   TextColor="#212121"
                   FontFamily="Roboto-Regular"
                   FontSize="14"
                   VerticalTextAlignment="Center" />


We’ve demonstrated this implementation in the attached sample, along with the corresponding output for your reference.


Best Regards,
Muthu Kumar Madasamy.

Attachment: SfChatSample_2d24fbe7.zip

Loader.
Up arrow icon