【发布时间】:2020-12-03 17:59:13
【问题描述】:
我有一个项目 (.NET Core 3.1.9),其中一个 FieldListener 组件嵌套在 EditForm 内。它像这样订阅 FieldChanged 事件:
@using Microsoft.JSInterop
@inject IJSRuntime JSRuntime
@code {
[CascadingParameter] EditContext CurrentEditContext { get; set; } //get cascaded edit context
private TestModel Model { get => CurrentEditContext != null ? (TestModel)CurrentEditContext.Model : new TestModel(); } //adds a getter to directly get the Model
protected override void OnInitialized() //called on component creation
{
CurrentEditContext.OnFieldChanged += FieldChanged;
}
private void FieldChanged(object sender, FieldChangedEventArgs args) //called whenever a form field changes
{
JSRuntime.InvokeVoidAsync("console.log", "FieldChanged Triggered. Model is: " + Model);
}
}
这适用于常规 InputText 组件,但不会触发这样的自定义组件:
<input type="text" class="form-control" @bind-value="text" />
@code {
[Parameter] public string Text { get; set; }
[Parameter] public EventCallback<string> TextChanged { get; set; }
private string text
{
get => Text;
set => TextChanged.InvokeAsync(value);
}
}
假设我的 EditForm 定义如下,如何使 FieldChanged 事件针对所有字段更改触发?
<EditForm EditContext="Context">
<FieldListener></FieldListener>
<p>Default text:</p>
<InputText class="form-control" @bind-Value="Model.Text"></InputText>
<p>Custom text with custom name binding:</p>
<CustomEditor2 @bind-Text="Model.Text3"></CustomEditor2>
</EditForm>
值得注意的是,所有字段更改仍会影响模型,但 FieldChanged 事件并不总是触发。
如果有帮助,这里有一个带有基本形式的测试项目来重现它:https://github.com/ThatFlashCat/CustomEditContextBindValue
【问题讨论】:
标签: asp.net-core blazor-server-side