从数据库 table 创建的 ObservableCollection 未更新

ObservableCollection created from database table not updating

在我的数据库助手 class 中,我设置了连接,创建 Table 和 ObservableCollection 对象并处理所有数据库操作:

public class ProfilesSourceSQLite : IProfilesSource
{
    private Table<ProfileManager.Profile> Profiles;
    private ObservableCollection<ProfileManager.Profile> profilesCollection;

    public ProfilesSourceSQLite()
    {
        ...
        Profiles = dbContext.GetTable<ProfileManager.Profile>();
        profilesCollection = new ObservableCollection<ProfileManager.Profile>(Profiles);
    }

    public ObservableCollection<ProfileManager.Profile> GetProfilesCollection()
    {
        return profilesCollection;
    }

    public bool AddProfile(ProfileManager.Profile profile)
    {
        try
        {
            Profiles.InsertOnSubmit(profile);
            dbContext.SubmitChanges();
        }
        ...
    }
}

我的问题是 profilesCollectionCollectionChanged 事件从未被触发。

public class ProfileManager
{
    private static ProfileManager instance;
    public static ProfileManager Instance
    {
        get
        {
            if (instance == null)
                instance = new ProfileManager();

            return instance;
        }
    }

    private ProfileManager()
    {
        ...
        profiles = new ProfilesSourceSQLite();
        profiles.GetProfilesCollection().CollectionChanged += ProfileManager_CollectionChanged;
    }

    private void ProfileManager_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        // MessageBox never appears
        MessageBox.Show("CHANGED!");
    }

    public bool AddProfile(Profile profile)
    {
        return profiles.AddProfile(profile);
    }
}

// Somewhere in the UI class
private void btnClicked()
{
    ProfileManager.Instance.AddProfile(newProfile);
}

我想让 profilesCollection 成为 ListViewItemsSource,这样我就不必关心处理项目列表的更改,但它也不起作用,因为它更简单例子。我究竟做错了什么?或者有更好的方法吗?

您正在更改集合中的项目,而不是集合本身。
您需要让 ProfileManager.Profile 实施 INotifyPropertyChanged 来满足您的要求。

祝你好运。

您犯了一个错误,即通过添加到 ObservableCollection<ProfileManager.Profile> 将自动更新的数据库。不会的。

当您调用 new ObservableCollection<ProfileManager.Profile>(Profiles); 时,它会在数据库中创建配置文件的快照。它不会为数据库创建任何 link,因此未来的数据库更新不会复制到集合中。

因此代码 Profiles.InsertOnSubmit(profile); dbContext.SubmitChanges(); 不会更新集合。因此它没有引发事件。