maui

Layout Label to wrap depending on other buttons


Considering the following code:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiApp1.MainPage">
    <VerticalStackLayout BackgroundColor="Gray"
            Spacing="10">
        <Editor x:Name="EditorText"
                VerticalOptions="Start"
                HeightRequest="80"
                BackgroundColor="White"/>
        <HorizontalStackLayout IsClippedToBounds="True">
            <Button Text="Button1"/>
            <Label FontSize="30"
                    Text="{Binding Text, Source={x:Reference EditorText}}"/>
            <Button Text="Button2"/>
        </HorizontalStackLayout>
        <Grid ColumnDefinitions="Auto,*,Auto">
            <Button Text="Button1"/>
            <Label Grid.Column="1" FontSize="30"
                    Text="{Binding Text, Source={x:Reference EditorText}}"/>
            <Button Grid.Column="2" Text="Button2"/>
        </Grid>
    </VerticalStackLayout>
</ContentPage>

Rendered depending on text size as: enter image description here

How can I have a mix of the two lines of UI ?: I want Button 2 close to the Label Text like in first line but if it exceeds the screen dimensions, the Label has to wrap like in second line.

I achieved this to work with code-behind calculation or using MaximumWidthRequest but I wonder if it exists a better solution using basic layout features..?


Solution

  • By setting HorizontalOptions to Start on the Grid, it will only take the necessary Width by default.

    <Grid ColumnDefinitions="Auto,*,Auto" HorizontalOptions="Start">
        <Button Text="Button1"/>
        <Label Grid.Column="1" FontSize="30"
            Text="{Binding Text, Source={x:Reference EditorText}}"/>
        <Button Grid.Column="2" Text="Button2"/>
    </Grid>
    

    That way the Label will only use the space it needs until it reaches its maximum width (or * in the ColumnDefinitions).

    enter image description here

    And if the text is long enough, it will reach its maximum width and the text will wrap:

    enter image description here