添加一些方法来指定 blazor 中的不确定复选框

M K*_*M K 4 asp.net-core blazor

添加某种方法来指定 blazor 中的不确定复选框。

我已经尝试过下面的代码,但它不起作用。

<input type="checkbox" indeterminate="@checkValue" onclick="@checkedClick" />

如何在 blazor 中指定不确定的复选框?

ker*_*ode 5

我看来这暂时还没有计划。(参见https://github.com/dotnet/aspnetcore/issues/10378

我找到的最小解决方案是这个......

元件代码

@inject IJSRuntime jsRuntime

<input @ref=inputElement type="checkbox" checked="@Checked" @onchange="OnChange" />

@code {
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (Indeterminate.HasValue)
        {
            await jsRuntime.SetElementProperty(inputElement, "indeterminate", Indeterminate.Value);
        }
        await base.OnAfterRenderAsync(firstRender);
    }

    private ElementReference inputElement;

    [Parameter]
    public bool? Indeterminate { get; set; }

    [Parameter]
    public bool Checked { get; set; }

    [Parameter]
    public EventCallback<bool> CheckedChanged { get; set; }

    private async Task OnChange(ChangeEventArgs e)
    {
        Checked = (bool)e.Value;
        await CheckedChanged.InvokeAsync(Checked);
    }
}
Run Code Online (Sandbox Code Playgroud)

互操作 C# 代码

public static async Task SetElementProperty(this IJSRuntime jsRuntime, ElementReference element, string property, object value)
{
    await jsRuntime.InvokeVoidAsync("window.jsinterop.setPropByElement", element, property, value);
}
Run Code Online (Sandbox Code Playgroud)

互操作 JavaScript 代码

window.jsinterop = {
    setPropByElement: function (element, property, value) {
        element[property] = value;
    }
}
Run Code Online (Sandbox Code Playgroud)