Home > Blockchain >  .NET MAUI: Check checkbox when clicking on label
.NET MAUI: Check checkbox when clicking on label

Time:10-01

Is there a way in .NET MAUI to toggle the state of a checkbox when the label next to it is clicked? As an example:

<?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="MyApp.Views.Test"
             Title="Test">
    <HorizontalStackLayout>
        <CheckBox />
        <Label Text="Check this box" VerticalOptions="Center" />
    </HorizontalStackLayout>
</ContentPage>

CodePudding user response:

You can use it like this , a Label and a CheckBox.

Give the CheckBox a Name.

 <Label
            Text="Check this box"
            FontSize="32"
            HorizontalOptions="Center" >
            <Label.GestureRecognizers>
                <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped"
                          NumberOfTapsRequired="1" />
            </Label.GestureRecognizers>
        </Label>
        
        <CheckBox x:Name="StackO" />

Then for the Label Tap

private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
    if (StackO.IsChecked )
       StackO.IsChecked = false;
    else
        StackO.IsChecked = true;
}

CodePudding user response:

Well basically you need to do something like this:

             <ContentView
                Padding="10,20">
                </pan:PancakeView.Border>
                <ContentView.GestureRecognizers>
                    <TapGestureRecognizer Command="{Binding SomeThingTappedCommand}" />
                </ContentView.GestureRecognizers>
                <StackLayout Orientation="Horizontal">
                    <Label
                        HorizontalOptions="StartAndExpand"
                        InputTransparent="True"
                        Text="Some Title"
                        VerticalTextAlignment="Center" />
                    <controls:ExtendedCheckBox
                        InputTransparent="True"
                        IsChecked="{Binding IsChecked}"
                        VerticalOptions="Center"
                        Color="{DynamicResource PrimaryColor}" />
                </StackLayout>
            </pan:PancakeView>

And then in your VM all you need to do is:

 SomeThingTappedCommand = new Command(() => IsChecked = !IsChecked);

Where IsChecked is a notifiable property:

 private bool isChecked;
 public bool IsChecked
    {
        get => isChecked;
        set => SetProperty(ref isChecked, value);
    }

Goodluck

  • Related