如何在Blazor组件上进行双向绑定

Ami*_*mam 2 c# blazor

我想创建自定义输入,因此创建了以下组件:

MyInputComponent.razor

<div>
  <input type="text" @bind="BindingValue" />
</div>

@code {
    [Parameter]
    public string BindingValue { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后的用法:

<EditForm Model="model" OnValidSubmit="Submit">
    <MyInputComponent BindingValue="model.Name" />
</EditForm>

@code {
    User model = new User() { Name = "My Name" };

    private void Submit()
    {
       // here I found model.Name = null;
   }
}
Run Code Online (Sandbox Code Playgroud)

调试时MyInputComponent,我发现了输入的值。但是当我提交表单时,该值为null。

怎么做 ?

Maj*_*jor 10

一般来说,接受的答案是正确的并且工作正常。唯一需要添加的是代码示例使用基于事件的默认名称约定,例如:{PropertyName}Changed

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

但是您可以覆盖此命名约定 @bind-{Property}:event="{EventCallbackName}"

<MyInputComponent @bind-BindingValue="model.Name" @bind-BindingValue:event="OnValueChanged"/>

.....

[Parameter] public EventCallback<string> OnValueChanged { get; set; }  
Run Code Online (Sandbox Code Playgroud)


rap*_*esa 9

将 Blazor 与 .NET7 结合使用,您可以执行以下操作:

MyCustomComponent.Razor

<input type="text" @bind:get="BindingValue" @bind:set="SetAsync">

@code {


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

async Task SetAsync(string value)=> await BindingValueChanged.InvokeAsync(value);
}
Run Code Online (Sandbox Code Playgroud)

}

然后你可以使用:

<MyCustomComponent @bind-BindingValue="whateverVariable" />                      
Run Code Online (Sandbox Code Playgroud)


dan*_*era 7

引用Blazor文档

组件参数

绑定识别组件参数,其中@ bind- {property}可以跨组件绑定属性值。

对于您的页面:

<EditForm Model="model" OnValidSubmit="Submit">
    <MyInputComponent @bind-BindingValue="model.Name" />
</EditForm>
Run Code Online (Sandbox Code Playgroud)

子组件MyInputComponent

<div>
  <InputText type="text" @bind-Value="@BindingValue" />
</div>

@code {

    private string _value;

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

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

}
Run Code Online (Sandbox Code Playgroud)

请注意,您应该从子组件引发绑定更改EventCallback<string> BindingValueChanged

在BlazorFiddle尝试一下

  • dani,如果您选择使用内置的 InputText 组件提供解决方案,那么为什么不建议继承 InputText 组件本身派生的类。它更简单,需要的代码更少,并且允许您根据需要控制输入 Html 标记的呈现,例如为密码创建自定义组件。更好的是,为什么不建议OP直接在EditForm中使用InputText组件......美好的一天。 (2认同)
  • @Issac,因为问题是**如何在Blazor组件上进行双向绑定** (2认同)