How to call CheckedChanged from MudCheckBox control – C#

by
Ali Hasan
blazor c# mudblazor

The Solutions:

Solution 1: Setters and Getters

To call the `CheckedChanged` event from a `MudCheckBox` control, you can utilize the new setters and getters. This approach involves binding to the `Checked` property both for getting and setting values.

<MudCheckBox @bind-Checked:get=context.IsCheckedTrue @bind-Checked:set=HandleCheck />

@code {
    private Task HandleCheck(bool value)
    {
        // Set the value in the model
        // Do what you want
        return Task.CompletedTask;
    }
}

Solution 2: Using `CheckedChanged` Event Handler

To call the `CheckedChanged` event from a `MudCheckBox` control, use the following syntax:


<MudCheckBox T="bool" Checked="CheckedVariable" Label="Your Label" CheckedChanged="@(e => OnCheckedChanged((bool)e))"></MudCheckBox>

In this example, `CheckedVariable` is a C# property that represents the checked state of the checkbox.

When the checkbox is clicked, the `CheckedChanged` event handler, `OnCheckedChanged()`, is invoked. This event handler can be used to update the `CheckedVariable` property and perform other business logic.

Solution 3: Handle CheckChanged event for MudCheckBox

To handle the `CheckedChanged` event for `MudCheckBox`, you can use the `@bind-Checked` attribute. This attribute allows you to bind the `Checked` property of the `MudCheckBox` to a property in your code-behind.

When the Checked property changes, the CheckedChanged event will be raised. You can handle this event in your code-behind by creating a method that takes a parameter of type bool (the new value of the Checked property) and then performing the desired actions.

Here is an example of how to use the @bind-Checked attribute to handle the CheckedChanged event for a MudCheckBox:

&lt;MudCheckBox @bind-Checked=&quot;@IsChecked&quot; @bind-CheckedChanged=&quot;HandleCheckedChanged&quot; Color=&quot;Color.Secondary&quot; CheckedIcon=&quot;@Icons.Material.Filled.RadioButtonChecked&quot; UncheckedIcon=&quot;@Icons.Material.Filled.RadioButtonUnchecked&quot;&gt;&lt;/MudCheckBox&gt;

@code {
    private bool IsChecked;

    private void HandleCheckedChanged(bool isChecked)
    {
        // Perform desired actions when the 'Checked' property changes
    }
}

Q&A

How to call CheckedChanged from MudCheckBox control?

You can use the new setters and getters or set the parameters directly or use the bind-Value:after event.

How to call CheckedChanged from MudCheckBox control in mudblazor?

You can use T="bool" and CheckedChanged="@(e => OnCheckedChanged((bool)e))" with custom event handler.

Can you give code example for CheckedChanged of MudSwitch?

MudSwitch can be binded to the property with custom getter and setter, inside which you can handle the CheckedChanged event.