[英]UI freezes while updating ObservableCollection
我知道,已經有很多關於這個主題的主題,但到目前為止我無法找到解決這個問題的方法。
首先,這是我的ItemsControl
:
<ScrollViewer Style="{StaticResource ScrollViewer}" VerticalScrollBarVisibility="Visible" MaxHeight="475">
<ItemsControl ItemsSource="{Binding CurrentSelectedItems}" Margin="0 10 0 0">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<controls:ItemControl />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
為簡單ItemsSource
, ItemsControl
的ItemsSource
屬性綁定到ItemViewModel
類型的ObservableCollection
。
ItemViewModel
包含大約 25 個屬性和一些Prism DelegateCommands
。
在ItemsControl
之上還有一些 Buttons 來改變CurrentSelectedItems
的內容。 由於這些項目有時總共多達 300 個,因此更新 UI 需要一些時間。 在這種情況下,應用程序 - 有原因 - 被凍結。
有沒有辦法不凍結 UI 和 eG 顯示微調器/加載消息?
提前致謝
編輯: controls:ItemControl
是一個簡單的自定義控件,包含大約 5 個Labels
和 3 個相當小的Images
盡管有其他答案,但無法避免這種情況。
WPF 是一個 SPA(單線程單元),這意味着任何 UI 對象都必須由 UI 線程創建和擁有。 當你有很多 UI 元素要構建和渲染時,UI 線程會很忙。
顯示 UI 加載動畫的解決方案也是不正確的,因為該動畫也將位於 UI 線程上,該線程已經忙於創建和渲染您的 UI 集合。
只要確保在后台線程上的任何處理,讓UI管理本身。
獲取 WPF Toolkit 並使用 BusyIndicator。 這將在您的控件頂部彈出一個窗口,並帶有一個移動的忙碌指示器。 您也可以使用它提供自定義消息。
您可以使用 task 來更新 UI,但它需要一個 List 參數。 去做這個:
// create an async method
private async void PopulateItems() {
// use task to populate the items
await Task.Run(() => {
for (var item in CurrentSelectedItems) {
this.Dispatcher.Invoke(() => yourItemCollectionControl.Add(item));
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.