John B
John B

Reputation: 49

net maui: Cannot dynamically create an instance of type ''. Reason: No parameterless constructor defined

when I click on the button to go to the page, an exception appears " System.MissingMethodException: "It is not possible to dynamically create an instance of the type 'MuseumFinder.Views.The museum list page for administrators". Reason: The constructor without parameters is not defined."

But I do not know how to fix it so that the view displays the result of the viewmodel and at the same time the transition to the page is carried out.

 private async void OnCounterClicked_1(object sender, EventArgs e)
    {
        await AppShell.Current.GoToAsync(nameof(MuseumListPageForAdmins));
    }
using MuseumFinder.ViewModels;

namespace MuseumFinder.Views;

public partial class MuseumListPageForAdmins : ContentPage
{
   

    private MuseumListPageViewModel _viewModel;
    public MuseumListPageForAdmins(MuseumListPageViewModel viewModel)
    {
        _viewModel = viewModel;
        this.BindingContext = viewModel;

    }
    protected override void OnAppearing()
    {
        base.OnAppearing();
        _viewModel.GetMuseumListCommand.Execute(null);

    }

 private readonly IMuseumService _museumService;
        public MuseumListPageViewModel(IMuseumService museumService)
        {
            _museumService = museumService;
        }

Upvotes: 0

Views: 2154

Answers (1)

TheKlinto
TheKlinto

Reputation: 49

The way your using it now looks like some Dependency Injection style, I haven't used before.

Appshell needs a parameterless constructor to create a new view. Since the routing is not passing any parameters, you don't need to specify the ViewModel in the constructor

Try the following code

using MuseumFinder.ViewModels;

namespace MuseumFinder.Views;

public partial class MuseumListPageForAdmins : ContentPage
{
   

    private MuseumListPageViewModel _viewModel = new();
    public MuseumListPageForAdmins()
    {
        InitializeComponent();
        BindingContext = _viewModel;
    }
    protected override void OnAppearing()
    {
        base.OnAppearing();
        _viewModel.GetMuseumListCommand.Execute(null);

    }

I've changed so the view makes a new instance of the viewmodel on creation and sets the BindingContexts to it.

EDIT: Remember the InitializeComponent() function to render the controls of the view. Nearly forgot it myself in the answer ;)

Upvotes: 0

Related Questions