Mike Tsayper
Mike Tsayper

Reputation: 1802

Community Toolkit popups slow down a MAUI app

Each time popup is shown, the time to show it increases. More elements in the popup, longer the time. I have made a demo app, showing a popup with 100 buttons. On my PC, the first launch takes about 300 ms which is fine, but this escalates quickly to several seconds and up. Popup code:

using CommunityToolkit.Maui.Views;
using System.Diagnostics;

namespace MauiApp2;

public partial class Popup1 : Popup
{
    Stopwatch sw = new();
    public Popup1()
    {
        sw.Start();
        InitializeComponent();
        Size = new Size(350, 500);
        for (int i = 0; i < 100; i++)
            Flex.Add(new Button() { Text = i.ToString() });
        Opened += (_, _) => Flex.Add(new Label() { Text = sw.ElapsedMilliseconds.ToString() });
    }
}

Markup:

<?xml version="1.0" encoding="utf-8" ?>
<toolkit:Popup xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
             x:Class="MauiApp2.Popup1">
        <FlexLayout x:Name="Flex" Wrap="Wrap"></FlexLayout>
</toolkit:Popup>

Main page code:

using CommunityToolkit.Maui.Views;

namespace MauiApp2;

public partial class MainPage : ContentPage
{
    public MainPage() => InitializeComponent();
    private void OnCounterClicked(object sender, EventArgs e)
    {
        var p = new Popup1();
        this.ShowPopup(p);
    }
}

How can it be fixed, or circumvented?

Upvotes: 0

Views: 657

Answers (1)

Mike Tsayper
Mike Tsayper

Reputation: 1802

My workaround i have came up with is to make elements static, add and remove them to/from the popup each time its shown. Not only it solves the slowdown problem but also speeds up the popup from the second opening and onwards (~20 ms on my PC)

using CommunityToolkit.Maui.Views;
using System.Diagnostics;

namespace MauiApp2;

public partial class Popup1 : Popup
{
    Stopwatch sw = new();
    static Button[] btns;

    static Popup1()
    {
        btns = Enumerable.Range(1, 100).Select(i => new Button() { Text = i.ToString() }).ToArray();
    }

    public Popup1()
    {
        sw.Start();
        InitializeComponent();
        Closed += Popup1_Closed;
        Size = new Size(350, 500);
        foreach (var b in btns) Flex.Add(b);
        Opened += (_, _) => Flex.Add(new Label() { Text = sw.ElapsedMilliseconds.ToString() });
    }

    private void Popup1_Closed(object sender, CommunityToolkit.Maui.Core.PopupClosedEventArgs e)
    {
        Flex.Clear();
        Flex.Parent = null;
    }
}

Upvotes: 0

Related Questions