0

I created a custom control in MAUI that must work if user select with a click or tap, a Popup must show with some content, let's say for example a Calculator instead a Keyboard. I'm using CommunityToolkit.Maui. But the sentence

var popup = new PickerControl();
var result = await PopupExtensions.ShowPopupAsync<PickerControl>(this, popup);

throw me an error because this in inside the control and expects a Page, so need to know how handle the page or parent page in the same control. Picker control is the Popup with the content. The code:

public partial class EntryCalculator : Frame
{
    TapGestureRecognizer _tapGestureRecognizer;
    public EntryCalculator()
    {
        InitializeComponent();
      }
///Properties here

    private void Initialize()
    {
        _tapGestureRecognizer = new TapGestureRecognizer();
    }

    
    private async static void IsDisplayPickerPropertyChanged(BindableObject bindable, object oldValue, object newValue)
    {
        var controls = (EntryCalculator)bindable;
        if (newValue != null)
        {
            if ((bool)newValue)
            {
                var popup = new PickerControl();
                var response = PopupExtensions.ShowPopupAsync<PickerControl>(this, popup);
                
               if (response != null && response is decimal)
                {
                    controls.Value = (decimal)response;
                }               
            }
        }
    } 
///... other methods

1 Answers1

1

At first, you can get the current page from the navigation stack:

If you use the shell:

Page currentpage = Shell.Current.Navigation.NavigationStack.LastOrDefault();

If you use the NavigationPage:

Page currentpage = Navigation.NavigationStack.LastOrDefault();

Or just only use:Page currentpage = App.Current.MainPage.Navigation.NavigationStack.LastOrDefault();. The App.Current.MainPage will be the Shell or the NavigationPage, it depends on what you used in your project.

In addition, you can get the current page from the custom control. Such as:

public static class ViewExtensions
{
    /// <summary>
    /// Gets the page to which an element belongs
    /// </summary>
    /// <returns>The page.</returns>
    /// <param name="element">Element.</param>
    public static Page GetParentPage (this VisualElement element)
    {
        if (element != null) {
            var parent = element.Parent;
            while (parent != null) {
                if (parent is Page) {
                    return parent as Page;
                }
                parent = parent.Parent;
            }
        }
        return null;
    }
}
Julian
  • 5,290
  • 1
  • 17
  • 40
Liyun Zhang - MSFT
  • 8,271
  • 1
  • 2
  • 14
  • In my case works the implentation of `ViewExtensions` class, because I have this custom controls in a different library. Thanks – Roberto Vargas Jan 03 '23 at 20:25