Custom Maui Handler control creates handler when used in xaml but when created with c# does not create the handler

Viewed 78

The repro is a small example based on the maui template. I created a button called MyButtonView and changed the MainPage to consume that control.

The button is created and shows correctly on the page, but when I try to create just the control as in var b = new MyButtonView(); the handler is not created and I cant figure out how to get this created.

Notice in the source I have implemented the clicked event to show how the handler is not created. I am sure I am missing something but could someone lead me in the right direction?

Github repro

1 Answers

So it seems that if the control once created has a null handler, you will need to call MyButtonView.ToHandler(mauiContext); sounds simple, but getting the mauiContext is a bit of a pain.

The only way i was able to do this was to do the following in the MauiProgram.cs. This works for windows, have yet to try it with iOS

    var builder = MauiApp.CreateBuilder();
    builder
        .UseMauiApp<App>()
        .ConfigureFonts(fonts =>
        {
            fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
            fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
        })
        .ConfigureMauiHandlers(handlers =>
        {
            handlers.AddHandler<DtNavigationView, DtNavigationViewHandler>();
            handlers.AddHandler<DtWindowTabView, DtWindowTabViewHandler>();
            handlers.AddHandler<DtWindowTabItem, DtWindowTabItemHandler>();
        });
    builder.UseMauiEmbedding<Application>();
    var mauiapp = builder.Build();
    mauiContext = new MauiContext(mauiapp.Services);
    return mauiapp;

Now you can use the static context to get the object to a handler, by using MyButtonView.ToHandler(MauiProgram.mauiContext);

Dont think this is the best way to do this but its all i can come up with for now.

Update - this is not the answer to the issue. Storing the MauiContext at this point will result in other issues such as not being able to have the base navigation framework setup.

So the only work around i have found so far that will work for me is to capture the MauiContext was to save it off in the handler when

public override void SetMauiContext(IMauiContext mauiContext) { DtMauiContext.mauiContext = mauiContext; base.SetMauiContext(mauiContext); }

The DtMauiContext is a static i can use it in the view level.

In the Maui source they have Application.Current.FindMauiContext(), it would have been so easy of they just exposed this.

Related