Reputation: 115
I want to display a community toolkit popup from a view model. The type of popup I want is a message box where I can pass a string variable that is the message I want displayed. I followed this Learn Popup Article from Microsoft, and I was able to build my popup and data bind the popup to a view model without any trouble. My problem comes when I try to display the popup from a different view model. Here is what I have so far:
Popup XAML
<ctm:Popup xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:ctm="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
xmlns:vwmod="clr-namespace:LockAndKeyMaui.ViewModels"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="LockAndKeyMaui.MsgBox"
x:DataType="vwmod:MsgViewModel"
CanBeDismissedByTappingOutsideOfPopup="False">
<VerticalStackLayout
WidthRequest="300" HeightRequest="200"
BackgroundColor="Blue">
<Label
Text="{Binding Msg}"
TextColor="Yellow"
VerticalOptions="Center"
HorizontalOptions="Center" />
</VerticalStackLayout>
</ctm:Popup>
Popup C#
using CommunityToolkit.Maui.Views;
using LockAndKeyMaui.ViewModels;
namespace LockAndKeyMaui;
public partial class MsgBox : Popup
{
readonly string MsgTxt;
public MsgBox(MsgViewModel msgvw)
{
InitializeComponent();
BindingContext = msgvw;
}
}
Popup View Model
using CommunityToolkit.Maui.Core;
using System.ComponentModel;
namespace LockAndKeyMaui.ViewModels
{
public class MsgViewModel : INotifyPropertyChanged
{
private string? msg;
readonly IPopupService popupService;
public string Msg
{
get => msg!;
set
{
msg = value;
OnPropChg(nameof(Msg));
}
}
public MsgViewModel(IPopupService popupService)
{
this.popupService = popupService;
}
public event PropertyChangedEventHandler? PropertyChanged;
private void OnPropChg(string prName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prName));
}
}
}
Now in a new view model I'm trying to use the command that the article shows which is this.popupService.ShowPopup<UpdatingPopupViewModel>(onPresenting: viewModel => viewModel.Name = "Shaun");
but I'm just trying to replace UpdatingPopupViewModel with UpdatingMsgViewModel and that's one of the red underlines I get. I replaced the line with this.popupService.ShowPopup<MsgViewModel>(onPresenting: viewModel => viewModel.Msg = "This is a test.");
and that's where the variable Msg does not exist.
I have the popup registered with builder.Services.AddTransient<MsgBox, MsgViewModel>();
in the MauiProgram.cs file.
So what am I missing? Thanks for the help.
Upvotes: 1
Views: 31