您需要正确地整理绑定,即设置getter以获取提供的
Value
设置器通过调用
ValueChanged
回拨。
下面是一个使用标准的示例
InputText
因为我不使用SF。我很确定SF TextBox的工作原理是一样的。我还展示了如何在不创建自定义控件的情况下实现您所展示的功能。
注意:一旦你正确理解了逻辑,就不需要乱打电话给
StateHasChanged
通过代码。
另请参阅此问答,其中显示了直接继承自Text控件的另一种方法-
https://stackoverflow.com/a/78661731/13065781
已设置绑定的基本自定义控件:
<InputText disabled="@IsDisabled" class="@CssClass"
placeholder="@this.Placeholder"
@bind-Value:get="@Value"
@bind-Value:set="SetValue"/>
@code {
[Parameter] public string? Value { get; set; }
[Parameter] public string? Placeholder { get; set; }
[Parameter] public string? CssClass { get; set; }
[Parameter] public EventCallback<string> ValueChanged { get; set; }
[Parameter] public bool IsDisabled { get; set; }
public bool IsEnabled => IsDisabled is false;
public async Task SetValue(string? value)
{
this.Value = value;
await ValueChanged.InvokeAsync(this.Value);
}
}
还有一个演示页面:
@page "/"
<PageTitle>Home</PageTitle>
<h1>Hello, world!</h1>
Welcome to your new app.
<EditForm Model="_model">
<div class="mb-2">
<InputText disabled="@_isDisabled"
class="form-control"
placeholder="Enter Your Name"
@bind-Value="_model.Name" />
</div>
<div class="mb-2">
<TextBoxBase CssClass="form-control"
IsDisabled="_isDisabled"
Placeholder="Enter A Value"
@bind-Value="_model.Value" />
</div>
</EditForm>
<div class="mb-2">
<button class="btn btn-primary" @onclick="OnDisable">Disable</button>
</div>
<div class="bg-dark text-white m-1 p-1">
<pre>Name: @_model.Name</pre>
<pre>Value: @_model.Value</pre>
</div>
@code {
private Model _model = new Model();
private bool _isDisabled;
private void OnDisable()
{
_isDisabled = !_isDisabled;
}
public class Model
{
public string? Name { get; set; }
public string? Value { get; set; }
}
}
最后一个音符。您不需要获取引用来编辑这样的组件:
public TextBoxBase SignInPasswordTextBox { get; set; }
一切都应该通过参数来实现。