默认情况下,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);
}
}