.NET MAUI Button Text Concatenation

Does anyone know how to create a button in .NET MAUI where the text of the button contains multiple elements?

For example, I want to create a button where it has an icon and text, The icon is a binding to a static resource. Looking around, it looks like you can do it by using multi bindings by adding direct content to the button element in XAML, but .NET MAUI give an error stating that you cannot set direct content on a button.

I have tried adding direct content to the button, but that didn't work and other than that - I couldn't find much else to try.

Please help.

Upvotes: 1

Views: 6657

Answers (2)

Luishg
Luishg

Reputation: 815

The native Button from MAUI (since .NET7 - tested on .NET8) has a ImageSource property which accepts a ImageSource and a FontImageSource. This means you can easily add an icon next to the text.

Example:

<Button Text="Take Picture"
        ContentLayout="Right, 10"
        Command="{Binding TakePhotoCommand}"
        Margin="10"
        FontSize="Medium">
    <Button.ImageSource>
        <FontImageSource Glyph="&#xf30c;" 
                         FontFamily="FontAwesomeRegular"/>
    </Button.ImageSource>
</Button>

Source: https://learn.microsoft.com/en-us/dotnet/maui/user-interface/controls/button?view=net-maui-8.0

Upvotes: 7

Isidoros Moulas
Isidoros Moulas

Reputation: 697

You best bet is to use either a VerticalStackLayout or a Grid including a label and the button.

<VerticalStackLayout>
    <Button/>
    <Label/>
</VerticalStackLayout>

or an example with Grid inside a border

<Border>
    <Grid>
       <Button VerticalOptions="Start"/>
       <Label VerticalOptions="End"/>
    </Grid>

    <Border.GestureRecognizers>
        <TapGestureRecognizer
             Tapped="TapGestureRecognizer_Tapped"
             Command="..."
             CommandParameter="..."/>
            
    </Border.GestureRecognizers>
</Border>

Also note that if the user taps the label and not the icon then your code will not execute. You have to include also code to your label. The same applies if the user taps the border.

hope that helps.

Upvotes: 4

Related Questions