如何更新blazor视图的可观察集合mvvm .net maui



我有一个集合,需要一点时间来填充,所以我想先在屏幕上显示其他数据,然后加载在该集合增量(我这样做与ajax和部分在web上,但这在。net maui应用程序不工作)。

//View:
<div class="container">
<p>@TestMessage</p>
@if (MyListOfItems != null)
{
@foreach (var item in MyListOfItems)
{
//display component
}
}
else
{
//loading placeholder
}
//rest of the view
</div>

//Code
@code{
private ObservableCollection<ListItemVM> MyListOfItems;
private string TestMessage;

protected override async Task OnInitializedAsync()
{
//Load the critical elements
//If I load the collection here then it takes too long
}
//This get's called after the OnInitialisedAsync 
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
TestMessage = "testing";
MyListOfItems = new ObservableCollection<ListItemVM>();
//I just want to load 10 elements initially
@for (int i = 0; i < 10; i++)
{
var newItem = someService.GetItemData();
//I was hoping at this point the view would update with the new item
MyListOfItems.Add(newItem); 
}
}
}
}

TestMessage更新,但集合没有!?如果我把TestMessage = "testing";放在for循环之后,那么TestMessage不会被更新。

我试过只在循环完成后更新集合,但这也不起作用。而且也不会给我想要的很好的增量加载效果。

var itemList = new ObservableCollection<ListItemVM>();    
@for (int i = 0; i < 10; i++)
{
var newItem = someService.GetItemData();
itemList.Add(newItem); 
}
MyListOfItems = itemList;

我做错了什么?我需要做这样的事情来显式绑定它吗?

@foreach (var item in Bind(x => x.MyListOfItems))

因为在xaml视图中你会这样做

<CollectionView ItemsSource="{Binding MyListOfItems}" />

这是一个非常基本的Razor路由组件,它演示了如何以"数据集"的形式增量更新UI。负载。我保持它尽可能简单,因为你还没有提供足够的细节,让我建立一个基于你的代码的工作模型:-)。

@page "/"
@using System.Diagnostics;
@using System.Text
@implements IDisposable
<h1>Slow Loading Record Set</h1>
@foreach (var message in this.Messages)
{
<div class="bg-dark text-white m-1 p-1">
@message
</div>
}
@code {
private List<string> Messages = new List<string>();
private bool cancel;
protected async override Task OnInitializedAsync()
{
this.Messages.Add($"Started Loading at {DateTime.Now.ToLongTimeString()}");
await LoadingSlowRecords();
this.Messages.Add($"Completed Loading at {DateTime.Now.ToLongTimeString()}");
}
private async Task LoadingSlowRecords()
{
for (var counter = 0; counter < 6; counter++)
{
if (cancel)
break;
await Task.Delay(3000);
this.Messages.Add($"New Record loaded at {DateTime.Now.ToLongTimeString()}");
Debug.WriteLine($"New Record loaded at {DateTime.Now.ToLongTimeString()}");
StateHasChanged();
}
}
public void Dispose()
{
Debug.WriteLine($"Dispose called at {DateTime.Now.ToLongTimeString()}");
cancel = true;
}
}

最新更新