每次执行仅使用数据绑定填充一次GridView

时间:2016-01-25 21:21:36

标签: c# sqlite xaml data-binding uwp

我目前正在使用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;
    }

1 个答案:

答案 0 :(得分:0)

以下是一种快速而简单的加载数据方法:

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}" />