Search code examples
maui

Execute a command on a checkbox in .Net Maui


I have a checkbox and this checkbox enables a border control that has date picker. To achieve this i have an observable boolean variable isEnabled, so i would like to change its value in the ViewModel, for this I have implemented Checkbox.Behaviors to execute my command when check changes. The problem i have is my command is not being executed.

`

 <HorizontalStackLayout Grid.Row="0"
                        Grid.Column="1">
                    <Label Text="Date To"
                           FontSize="18"
                           Padding="0,0,60,0"/>
                    <CheckBox x:Name=" chkDate"
                        IsChecked="true"
                              HorizontalOptions="End">
                        <CheckBox.Behaviors>
                            <toolkit:EventToCommandBehavior
                                EventName="CheckedChanged"
                                CommandParameter="{Binding Source={x:Reference chkDate},Path=State}"
                                Command="{Binding SelectDateCommand}"/>                        
                        </CheckBox.Behaviors>
                    </CheckBox>
                </HorizontalStackLayout>

below is my Command

[RelayCommand]
        async Task SelectDateAsync(bool state)
        {
            try
            {
                IsEnabled = state;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                await Shell.Current.DisplayAlert("Checkout", "shipto selection failed please try again or contact Khayah Cement", "OK");
            }
        }

Solution

  • I tried with receiving an Object parameter which works:

    [RelayCommand]
    async Task SelectDateAsync(object s)
    {
        try
        {
            bool state = (bool)s;
            IsEnabled = state;
        }
        catch (Exception ex)
        {
             ....
        }
    }
    

    Also change the CommandParameter binding as FreakyAli said

    CommandParameter="{Binding Source={x:Reference chkDate}, Path=IsChecked}"
    

    Hope it works for you.