如何在单选按钮 Blazor 子组件上进行双向绑定

How to do two-way binding on a radio button Blazor child component

我正在尝试在 Blazor 中创建一个具有双向数据绑定的单选按钮组件,但我似乎无法获取要更改的父项上的值 (testNumber)。我是 Blazor 和 C# 的新手,所以非常感谢任何帮助。谢谢

ChildComp.razor

<div>
    <label for="radio1">1</label>
    <input 
        id="radio1"
        type="radio"
        value="1"
        name="test"
        checked="@(_selectedGroup == 1)"
        @onclick="@(() => _selectedGroup = 1)"/>

    <label for="radio2">2</label>
    <input
        id="radio2"
        type="radio"
        value="2"
        name="test"
        checked="@(_selectedGroup == 2)"
        @onclick="@(() => _selectedGroup = 2)"/>

</div>

@code {

    private int _selectedGroup = 0;

    [Parameter]
    public int BindingValue
    {
        get => _selectedGroup;
        set
        {
            if (_selectedGroup == value ) 
            {
                return;
            }
            else
            {
                _selectedGroup = value;
            }
            BindingValueChanged.InvokeAsync(value);
        }
    }

    [Parameter]
    public EventCallback<int> BindingValueChanged { get; set; }   
}

ParentComp.razor

<div>
    <ChildComp @bind-BindingValue="testNumber" />
    <h5>@testNumber</h5> 
</div>

@code {

    int testNumber = 0;
}

您可能已经注意到 bind 不适用于单选按钮。在 GitHub 上你可以看到关于它的讨论 here。很遗憾 Blazor 不支持这些简单的功能...

我遇到了同样的问题并遇到了这个 solution:

@code {
    public int EditionCode = 1;

    // "Edition" class has "int Code" and "string Text" properties.
    public Edition[] Editions = new [] {
      new Edition { Code = 1, Text = "Home" },
      new Edition { Code = 2, Text = "Pro" },
      new Edition { Code = 3, Text = "Enterprise" },
    };
}

@foreach (var edition in this.Editions)
{
<label>
  <input type="radio" 
         name="edition"
         checked="@(EditionCode == edition.Code)"
         onchange="@(() => EditionCode = edition.Code)"/>
         @edition.Text
</label>
}

如果此解决方案不能解决您的需求,请查看here(有点复杂)。