最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - Error When Using IPopupService with Custom Popup - Stack Overflow

programmeradmin13浏览0评论

I am getting the following error when calling the ShowPopupAsync method.

{System.Collections.Generic.KeyNotFoundException: The given key 'SimplePopup.ViewModel.SimplePopupViewModel' was not present in the dictionary.

The code is being called from a button clicked event as shown below:

private async void Button_Clicked(object sender, EventArgs e)
 {
     try
     {
         var result = await _popupService.ShowPopupAsync<SimplePopupViewModel>(onPresenting: _viewModel => _viewModel.Name = "John Smith");
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }

The Popup XAML is:

<?xml version="1.0" encoding="utf-8" ?>
<toolkit:Popup
    x:Class="SimplePopup.SimplePopup"
    xmlns=";
    xmlns:x=";
    xmlns:viewModel="clr-namespace:SimplePopup.ViewModel"
    xmlns:toolkit=";>
    
    <VerticalStackLayout>
        <Label
            HorizontalOptions="Center"
            Text="{Binding Name}"
            VerticalOptions="Center" />

        <Button Text="Yes" />
        <Button Text="No" />

    </VerticalStackLayout>
</toolkit:Popup>

The popup view model just has a single name property or receiving the data into.

using CommunityToolkit.Mvvm.ComponentModel;

namespace SimplePopup.ViewModel
{
    public partial class SimplePopupViewModel : BaseViewModel
    {
        public SimplePopupViewModel()
        {

        }

        [ObservableProperty]
        string name;
    }
}

It doesn't seem to matter what parameters are passed to ShowPopupAsync it always returns the same error. I need to be able to return a value to the caller (i.e. which button has been clicked and pass display data to the popup).

Is there something missing or is there a better way to do this?

using CommunityToolkit.Maui;
using Microsoft.Extensions.Logging;
using SimplePopup.ViewModel;

namespace SimplePopup
{
    public static class MauiProgram
    {
        public static MauiApp CreateMauiApp()
        {
            var builder = MauiApp.CreateBuilder();
            builder
                .UseMauiApp<App>()
                .UseMauiCommunityToolkit()
                .ConfigureFonts(fonts =>
                {
                    fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                    fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
                });

#if DEBUG
            builder.Logging.AddDebug();
#endif
            builder.Services.AddSingleton<MainPage>();
            builder.Services.AddSingleton<MainPageViewModel>();
            builder.Services.AddTransient<SimplePopup, SimplePopupViewModel>();
            return builder.Build();
        }
    }
}

I am getting the following error when calling the ShowPopupAsync method.

{System.Collections.Generic.KeyNotFoundException: The given key 'SimplePopup.ViewModel.SimplePopupViewModel' was not present in the dictionary.

The code is being called from a button clicked event as shown below:

private async void Button_Clicked(object sender, EventArgs e)
 {
     try
     {
         var result = await _popupService.ShowPopupAsync<SimplePopupViewModel>(onPresenting: _viewModel => _viewModel.Name = "John Smith");
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }

The Popup XAML is:

<?xml version="1.0" encoding="utf-8" ?>
<toolkit:Popup
    x:Class="SimplePopup.SimplePopup"
    xmlns="http://schemas.microsoft/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft/winfx/2009/xaml"
    xmlns:viewModel="clr-namespace:SimplePopup.ViewModel"
    xmlns:toolkit="http://schemas.microsoft/dotnet/2022/maui/toolkit">
    
    <VerticalStackLayout>
        <Label
            HorizontalOptions="Center"
            Text="{Binding Name}"
            VerticalOptions="Center" />

        <Button Text="Yes" />
        <Button Text="No" />

    </VerticalStackLayout>
</toolkit:Popup>

The popup view model just has a single name property or receiving the data into.

using CommunityToolkit.Mvvm.ComponentModel;

namespace SimplePopup.ViewModel
{
    public partial class SimplePopupViewModel : BaseViewModel
    {
        public SimplePopupViewModel()
        {

        }

        [ObservableProperty]
        string name;
    }
}

It doesn't seem to matter what parameters are passed to ShowPopupAsync it always returns the same error. I need to be able to return a value to the caller (i.e. which button has been clicked and pass display data to the popup).

Is there something missing or is there a better way to do this?

using CommunityToolkit.Maui;
using Microsoft.Extensions.Logging;
using SimplePopup.ViewModel;

namespace SimplePopup
{
    public static class MauiProgram
    {
        public static MauiApp CreateMauiApp()
        {
            var builder = MauiApp.CreateBuilder();
            builder
                .UseMauiApp<App>()
                .UseMauiCommunityToolkit()
                .ConfigureFonts(fonts =>
                {
                    fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                    fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
                });

#if DEBUG
            builder.Logging.AddDebug();
#endif
            builder.Services.AddSingleton<MainPage>();
            builder.Services.AddSingleton<MainPageViewModel>();
            builder.Services.AddTransient<SimplePopup, SimplePopupViewModel>();
            return builder.Build();
        }
    }
}
Share Improve this question edited Mar 28 at 10:46 phm asked Mar 27 at 10:32 phmphm 233 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

That because the Popup View and Popup ViewModel haven't been registered with the MauiAppBuilder.

You can just add the following code in the MauiProgram.cs file,

builder.Services.AddTransientPopup<MyPopup, SimplePopupViewModel>(); 

And the error will disappear.

For more info, please refer to Registering a Popup, Register Popup View and View Model.


You can also pass a parameter to the popup,

var name = "" // set it to anything you want 
var result = await _popupService.ShowPopupAsync<SimplePopupViewModel>(onPresenting: _viewModel => _viewModel.Name = name);

Hope it helps!

发布评论

评论列表(0)

  1. 暂无评论