每次执行时仅使用数据绑定填充一次 GridView
本文关键字:一次 GridView 填充 执行 数据绑定 | 更新日期: 2023-09-27 18:31:47
我目前正在使用 XAML 和 C# 制作 UWP 应用程序,但我遇到了一个主要问题。主页包含 700+ 项,所有项都存储在 SQLite 数据库中并在运行时填充。每次我导航并返回页面时,应用程序都会冻结一段时间,然后显示主页......我怎么能只填充一次,即使它占用了我所有的启动时间?
我的填充代码看起来像这样(在 *.xaml.cs 中):
public sealed partial class MainView : Page
{
// Creates the Collection
public System.Collections.ObjectModel.ObservableCollection<sqlitetable> chooseaname = new System.Collections.ObjectModel.ObservableCollection<sqlitetable>();
public MainView()
{
this.InitializeComponent();
// Populates the Collection
using (var db = new SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), System.IO.Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, "Assets", "database.db")))
{
foreach (var entry in db.Table<sqlitetable>())
{
chooseaname.Add(new sqlitetable { Image = "/Assets/pics/" + entry.ID + ".png", Name = entry.Name, Type1 = "/Assets/Types/" + entry.Type1 + ".png", Type2 = "/Assets/Types/" + entry.Type2 + ".png", dummyID = "# " + entry.ID.ToString("000") });
}
}
// Sets the binding
mainView.ItemsSource = chooseaname;
}
这是一种仅加载一次数据的快速而肮脏的方法:
public sealed partial class MainView : Page
{
private static IList<sqlitetable> data = null;
public IList<sqlitetable> Data
{
get
{
if (data == null)
{
data = new List<sqlitetable>();
// Populates the Collection
using (var db = new SQLiteConnection(new SQLitePlatformWinRT(), Path.Combine(Package.Current.InstalledLocation.Path, "Assets", "database.db")))
{
foreach (var entry in db.Table<sqlitetable>())
{
data.Add(new sqlitetable { Image = "/Assets/pics/" + entry.ID + ".png", Name = entry.Name, Type1 = "/Assets/Types/" + entry.Type1 + ".png", Type2 = "/Assets/Types/" + entry.Type2 + ".png", dummyID = "# " + entry.ID.ToString("000") });
}
}
}
return data;
}
}
public MainView()
{
this.InitializeComponent();
gridView.ItemsSource = Data;
}
}
请考虑将数据存储在单独的视图模型类中,并使用单一实例模式或依赖项注入框架实例化一次。它不会更好地工作,但会通过分离关注点来提高可维护性。
还可以考虑从 XAML 绑定到数据,而不是在代码中设置ItemsSource
,例如:
<GridView ItemsSource="{x:Bind Data, Mode=OneTime}" />