Search code examples
c#data-bindingblazormaui

How to two-way bind a checkbox to a boolean in MAUI Blazor


In my MAUI Blazor App, I just want to bind a boolean value to a checkbox - and tried a lot with OnChange-Functions, with [Parameter] and individual getter and setter. But nothing works.

I just want to bind the checked status of a checkbox to a boolean in two-way binding.

That's what I have - and what's not working:

<input type="checkbox" @bind-value="@IsChecked" @bind-value:after="CheckboxChanged">
<button @onclick="Toggle">Toggle</button>

@code
{

    [Parameter]
    public bool IsChecked { get; set; } = true;
    private void CheckboxChanged()
    {
        Console.WriteLine($"Checkbox changed {IsChecked}");
    }


    protected void Toggle()
    {
        IsChecked = !IsChecked;
        Console.WriteLine($"--- Toggle: {IsChecked}");
    }

}

The button and toggle function is for testing purposes only - later the IsChecked should be changed by my logic programmatically (e.g. reading from storage on startup and writing boolean to storage on change)


Solution

  • I can reproduce your problem. You are mixing bind and @bind notations, so you can change @bind-value to @bind:

    <input type="checkbox" @bind="@IsChecked" @bind:after="CheckboxChanged">
    <button @onclick="Toggle">Toggle</button>
    
    @code
    {
    
        [Parameter]
        public bool IsChecked { get; set; } = true;
        private void CheckboxChanged()
        {
            Console.WriteLine($"Checkbox changed {IsChecked}");
        }
    
    
        protected void Toggle()
        {
            IsChecked = !IsChecked;
            Console.WriteLine($"--- Toggle: {IsChecked}");
        }
    
    }