默认情况下,Blazor 在按钮单击等许多场景中自动检测必要的 UI 刷新。但是,在某些情况下,您希望使用该BlazorComponent.StateHasChanged方法手动触发 UI 刷新。
在以下示例中,它使用计时器更改应用程序的状态。
@page "/refresh-ui-manually"
@using System.Threading;
<h1>@Count</h1>
<button onclick=@StartCountdown>Start Countdown</button>
@functions {
private int Count { get; set; } = 10;
void StartCountdown()
{
var timer = new Timer(new TimerCallback(_ =>
{
if (Count <= 0) return;
Count--;
// Note that the following line is necessary because otherwise
// Blazor would not recognize the state change and not refresh the UI
this.StateHasChanged();
}), null, 1000, 1000);
}
}
参考链接:https://blazor-tutorial.net/refresh-ui-manually
相关阅读
- Blazor WebAssembly 使用SignalR同步获取摄像头信息
- 在Blazor中如何设置event.PreventDefault来防止冒泡
- Blazor 学习资源汇总:入门教程、官方文档与实战示例