In my MAUI mobile app I have a page with a ContentView. I need to be able to swap the content out many times. But each view I’m using isn’t being garbage collected after being shown and then replaced by another view, so the app eventually fails due to memory issues.
Am I going about being able to swap out a subview incorrectly?
The code demonstrates a simplified version of what I’m trying to do.
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ViewSwapTest.MainPage">
<ScrollView>
<VerticalStackLayout
Padding="30,0"
Spacing="25">
<ContentView
x:Name="ContentView"
HeightRequest="100"
WidthRequest="100" />
<Button
x:Name="Button1"
Text="1"
Clicked="OnButton1Hit"
HorizontalOptions="Fill" />
<Button
x:Name="Button2"
Text="2"
Clicked="OnButton2Hit"
HorizontalOptions="Fill" />
</VerticalStackLayout>
</ScrollView>
</ContentPage>
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private View lastView;
private void OnButton1Hit(object sender, EventArgs e)
{
lastView = null;
lastView = new BlueView();
ContentView.Content = lastView;
}
private void OnButton2Hit(object sender, EventArgs e)
{
lastView = null;
lastView = new RedView();
ContentView.Content = lastView;
}
}
3