.NET MAUI Chat MVVM Support
With the RadChat
control, you can use the Model-View-ViewModel (MVVM) pattern. You can achieve this through the ItemsSource
property that can be bound or set to a collection of data items that will be converted into Chat items.
The following example shows how to use RadChat
in MVVM scenarios.
1. Create a sample class used to hold the needed information for the Chat items:
public class SimpleChatItem
{
public Author Author { get; set; }
public string Text { get; set; }
}
2. Create a ViewModel containing a collection of your SimpleChatItem
items. You can also bind the Chat's Author
property that represents the end user typing in the input field.
public class ViewModel : NotifyPropertyChangedBase
{
private Author me;
public ViewModel()
{
this.Me = new Author() { Name = "human", Avatar = "sampleavatar.png" };
this.Bot = new Author() { Name = "Bot", Avatar = "samplebot.png" };
this.Items = new ObservableCollection<SimpleChatItem>();
// Simulate async data loading
Device.StartTimer(TimeSpan.FromMilliseconds(500), () =>
{
this.Items.Add(new SimpleChatItem { Author = this.Bot, Text = "Hi." });
this.Items.Add(new SimpleChatItem { Author = this.Bot, Text = "How can I help you?" });
return false;
});
}
public Author Me
{
get
{
return this.me;
}
set
{
if (this.me != value)
{
this.me = value;
this.OnPropertyChanged(nameof(this.Me));
}
}
}
public Author Bot { get; set; }
public IList<SimpleChatItem> Items { get; set; }
}
3. Create a Converter
class of type IChatItemConverter
to convert the data items into Chat messages and the other way around:
public class SimpleChatItemConverter : IChatItemConverter
{
public ChatItem ConvertToChatItem(object dataItem, ChatItemConverterContext context)
{
SimpleChatItem item = (SimpleChatItem)dataItem;
TextMessage textMessage = new TextMessage()
{
Data = dataItem,
Author = item.Author,
Text = item.Text
};
return textMessage;
}
public object ConvertToDataItem(object message, ChatItemConverterContext context)
{
ViewModel vm = (ViewModel)context.Chat.BindingContext;
return new SimpleChatItem { Author = vm.Me, Text = (string)message, };
}
}
4. Add the RadChat
control to your page with previously defined ItemsSource
and ItemConverter
properties:
<telerik:RadContentView.Resources>
<ResourceDictionary>
<local:SimpleChatItemConverter x:Key="SimpleChatItemConverter" />
</ResourceDictionary>
</telerik:RadContentView.Resources>
<telerik:RadChat x:Name="chat"
Author="{Binding Me}"
ItemsSource="{Binding Items}"
ItemConverter="{StaticResource SimpleChatItemConverter}">
<telerik:RadChat.BindingContext>
<local:ViewModel />
</telerik:RadChat.BindingContext>
</telerik:RadChat>