Esteban Chornet
Esteban Chornet

Reputation: 1237

Xamarin forms view optimization when IsVisible=false

I'm looking for best practice in order to optimize Xamarin Forms app when switching visibility of layouts in order to show them when screen resizing. Xamarin Forms loads any layout either if IsVisible=false. So, what I'm looking to optimize my app is, load layouts when IsVisible=True, if it turns to False, is there a way to "unload" it so it does not take too much memory of a device? Because there's no problem with UWP, but there are phones with low memory.

Let's suppose I have next code:

    <StackLayout IsVisible="False" Orientation="Vertical">
        <!-- Make it visible when small screen -->
        <CustomView1></CustomView1>
        <CustomView2></CustomView2>
    </StackLayout>

    <StackLayout IsVisible="True" Orientation="Horizontal">
        <!-- Make it NON visible when small screen -->
        <CustomView1></CustomView1>
        <CustomView2></CustomView2>
    </StackLayout>

Xamarin would load same views 2 times. What I'm looking is like in web, remove it from the DOM (or dont load it in the DOM until it's visible), but for Xamarin Forms. So the app does not load the view when it does not need it, and I'm looking to have it while runtime, on the window app resize.

PS: It could be done by making use of OnIdiom.Phone, OnIdiom.Tablet and OnIdiom.Desktop, but this last, I could not have the view as desired if UWP window app resize.

Upvotes: 1

Views: 1162

Answers (2)

Nick Kovalsky
Nick Kovalsky

Reputation: 6462

You can define your visual states for normal screen, large screen etc, they will show or not depending on current state:

Use the Visual State Manager to make changes to XAML elements based on visual states set from code.

The Visual State Manager (VSM) is new in Xamarin.Forms 3.0. The VSM provides a structured way to make visual changes to the user interface from code. In most cases, the user interface of the application is defined in XAML, and this XAML includes markup describing how the Visual State Manager affects the visuals of the user interface.

https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/visual-state-manager

Upvotes: 1

Esteban Chornet
Esteban Chornet

Reputation: 1237

You can use Control Templates to change the appearance of a view/page at runtime. This is helpful if you want to re-theme pages or switch between views depending on the context. The property that allows to set a control template is called ControlTemplate which is available in ContentPage and ContentView classes.

Ref: https://www.xamboy.com/2019/01/18/using-control-templates-in-xamarin-forms/

Upvotes: -1

Related Questions