在Blazor中,使用Data Binding时,组件需要通知框架当绑定的数据发生变化时它需要重新渲染。如果不通过通知框架的方式告知它,那么Blazor组件就无法发现发生的数据变化。
通常Blazor使用INotifyPropertyChanged来做到这一点。INotifyPropertyChanged接口提供事件PropertyChanged,当更改属性的值时,它会触发该事件。可以使用它来告知组件有属性更改了。
在以下示例中,当Web API返回数据时,刷新List的UI元素。
public class ExampleComponent : ComponentBase
{
private List _examples;
protected async override Task OnInitializedAsync() {
_examples = await HttpClient.GetJsonAsync>("api/example");
}
private void RefreshComponent() {
StateHasChanged();
}
}
public class ExampleModel {
public int Id { get; set; }
public string Name { get; set; }
}