我仍然很难绑定到一个简单的标签。这个问题看起来很简单,但我已经浪费了几天时间,所以是时候寻求帮助了。也许有人知道答案。
在下面的代码中,按钮每次都有效,但按 Enter 不会更新页面,即使绑定到标签的变量已更改(我已通过使用 Serilog 打印到控制台来检查)
简而言之:按钮和回车键正确调用完全相同的函数,每次都会完成这项工作。不幸的是,页面只能通过更改标签的状态来感知按钮的变化。
现在,如果我按 Enter 两次,那么它似乎可以工作,但它不会向您显示在后台存在异常,因为它已经是重复的值。第三次按 Enter 键即可得到正确的状态。
请记住,我是 C# 新手,特别是 Maui Blazor 混合应用程序。
谢谢!
html:
<div> <button @onclick=PushToDatabaseFunction> upload to db </button> <input @onkeyup="@(e => KeyPressHandler("inputFieldForUploading", e))" @bind-value:event="oninput" @bind-value="inputFieldString" type="text" placeholder="..." /> </div> <div> <label>Status Label: @statusLabelBindString</label> </div>
在我的代码上:
private string statusLabelBindString = ""; private string inputFieldString = ""; private async void KeyPressHandler(string inputField, KeyboardEventArgs e) { if (e.Key == "Enter") { if (inputField == "inputFieldForUploading") await PushToDatabaseFunction(); } } private async Task PushToDatabaseFunction() { //code here takes the inputFieldString and adds it to a database //I've triple checked many many times and the code to the db works correctly db.insert(inputFieldString); //the following line also works correctly, as the statusLabelBindString variable > // takes on a new value. if(db.status=="ok") statusLabelBindString = $" {inputFieldString} was added to db"; else statusLabelBindString = "Error - Duplicate value"; //Even though statusLabelBindString has a new value (I've checked), the label does not //update if you press Enter, but from the button it works fine. }
可能是怎么回事?
谢谢!
首先,我用
await Task.Delay(1000);
重现了你的问题:
private async Task PushToDatabaseFunction() {
await Task.Delay(1000);
statusLabelBindString = $" {inputFieldString} was added to db";
}
上面的代码可以重现您的问题。我可以通过两种方式解决它:
StateHasChanged()
,你也可以尝试一下:if(db.status=="ok")
{
statusLabelBindString = $" {inputFieldString} was added to db";
StateHasChanged();
}
else{
statusLabelBindString = "Error - Duplicate value";
StateHasChanged();
}
await
中的await Task.Delay(1000);
:private async Task PushToDatabaseFunction() {
Task.Delay(1000);
statusLabelBindString = $" {inputFieldString} was added to db";
}
这两种方式都可以在您第一次按 Enter 时自动更新标签。
所以问题出在异步方法上。 UI 永远不会刷新(重新渲染),因为运行时永远不会调用
StateHasChanged()
,因为运行时不知道异步方法何时调用返回。