I’m trying to create a message box that would display varied messages and headers. So what I’m kind of looking for is a way to data bind the displayed label controls in the XAML file.
Here’s what I have so far:
<?xml version="1.0" encoding="utf-8" ?>
<ctm:Popup xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:ctm="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
xmlns:viewmodel="clr-namespace:LockAndKeyMaui.ViewModels"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="LockAndKeyMaui.MsgBox"
CanBeDismissedByTappingOutsideOfPopup="False"
Color="Blue">
<VerticalStackLayout>
<Label
Text="Success!"
Margin="5,5,0,0" FontSize="20"
FontAttributes="Bold" FontFamily="Arial"
TextColor="White" x:Name="lblHdr"/>
<Label
Text="Completed Successfully..."
HorizontalOptions="Center"
VerticalOptions="Center"
FontSize="16" FontFamily="Arial"
TextColor="Yellow" x:Name="lblMsg"/>
</VerticalStackLayout>
</ctm:Popup>
And my view model:
using CommunityToolkit.Maui.Core;
using System.ComponentModel;
namespace LockAndKeyMaui.ViewModels
{
public partial class MsgViewModel : INotifyPropertyChanged
{
private string? msgtxt, hdrtxt;
public string MsgTxt
{
get => msgtxt!;
set
{
msgtxt = value;
OnPropChg(nameof(MsgTxt));
}
}
public string HdrTxt
{
get => hdrtxt!;
set
{
hdrtxt = value;
OnPropChg(nameof(HdrTxt));
}
}
private readonly IPopupService popupService;
public MsgViewModel(IPopupService popupService)
{
this.popupService = popupService;
}
public void DisplayPopup(string ptxt, string phdr = "")
{
this.popupService.ShowPopup<MsgViewModel>(onPresenting: vwMod => vwMod.PerformUpdts(ptxt, phdr));
}
public void PerformUpdts(string txt, string hdr = "")
{
HdrTxt = hdr;
MsgTxt = txt;
}
public event PropertyChangedEventHandler? PropertyChanged;
private void OnPropChg(string prName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prName));
}
}
}
So when I display the popup I would want to do something like this:
DisplayPopup("User Name has been copied.", "Copied");
Task.Delay(2000);
Close();
return;
And somehow bind the two input strings to the label controls. How can I do this?
Also, this DisplayPopup
method is written in the MsgViewModel file. How can I access it from a different view model?