问题
I want to create custom input, so I created this component:
MyInputComponent.razor
:
<div>
<input type="text" @bind="BindingValue" />
</div>
@code {
[Parameter]
public string BindingValue { get; set; }
}
Then the usage:
<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;
}
}
When I debug MyInputComponent
, I found the value as I have entered. But when I submit the form, the value is null.
How to do it ?
回答1:
Quoting Blazor docs:
Component parameters
Binding recognizes component parameters, where @bind-{property} can bind a property value across components.
For your page:
<EditForm Model="model" OnValidSubmit="Submit">
<MyInputComponent @bind-BindingValue="model.Name" />
</EditForm>
The child component 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; }
}
Notice you should to raise binding changes from children component through EventCallback<string> BindingValueChanged
.
Try it at BlazorFiddle.
来源:https://stackoverflow.com/questions/57932850/how-to-make-two-way-binding-on-blazor-component