C# MAUI 快速批量更新 ObservableCollection 變數 【避免clear 和 Add 操作 都會導致 UI 重新繪製】 範例
C# MAUI 快速批量更新 ObservableCollection 變數 【避免clear 和 Add 操作 都會導致 UI 重新繪製】 範例
資料來源: Copilot
01.建立模型類別:
public class Person { public string Name { get; set; } public int Age { get; set; } }
02.在 UI 中綁定 ObservableCollection:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="YourNamespace.MainPage"> <StackLayout> <Button Text="Update People" Clicked="OnUpdatePeopleClicked" /> <ListView ItemsSource="{Binding People}"> <ListView.ItemTemplate> <DataTemplate> <TextCell Text="{Binding Name}" Detail="{Binding Age}" /> </DataTemplate> </ListView.ItemTemplate> </ListView> </StackLayout> </ContentPage>
03.擴展 ObservableCollection:
public class BulkObservableCollection<T> : ObservableCollection<T> { private bool _suppressNotification = false; protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { if (!_suppressNotification) { base.OnCollectionChanged(e); } } public void AddRange(IEnumerable<T> items) { _suppressNotification = true; foreach (var item in items) { Add(item); } _suppressNotification = false; OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } public void ClearAndAddRange(IEnumerable<T> items) { _suppressNotification = true; Clear(); foreach (var item in items) { Add(item); } _suppressNotification = false; OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } }
04.使用 BulkObservableCollection: (重點在註解之上)
public ObservableCollection<Person> People { get; set; }//宣告時使用ObservableCollection public MainPage() { InitializeComponent(); People = new BulkObservableCollection<Person> { new Person { Name = "Alice", Age = 30 }, new Person { Name = "Bob", Age = 25 }, new Person { Name = "Charlie", Age = 22 } }; //new 時 要使用BulkObservableCollection來建立物件 BindingContext = this; } public void UpdatePeople() { var updatedPeople = new List<Person> { new Person { Name = "David", Age = 35 }, new Person { Name = "Eva", Age = 28 }, new Person { Name = "Frank", Age = 24 } }; ((BulkObservableCollection<Person>)People).ClearAndAddRange(updatedPeople);//更新資料語法 }
重點再次整理:
宣告時使用ObservableCollection
new 時 要使用BulkObservableCollection來建立物件
One thought on “C# MAUI 快速批量更新 ObservableCollection 變數 【避免clear 和 Add 操作 都會導致 UI 重新繪製】 範例”
為了克服 Maui.DataGrid 物件查詢時更新/渲染 UI 太慢的問題