简体   繁体   English

不断更新ListView的ItemsSource吗?

[英]Update ListView's ItemsSource Constantly?

I have a ListView that I set it's ItemsSource to list all the Assignments (a table in my SQL Database, ORM is LINQ to SQL) like so: 我有一个ListView,将其设置为ItemsSource,以列出所有工作分配(在我的SQL数据库中的表,ORM是LINQ to SQL),如下所示:

ltvAssignments.ItemsSource = _repo.ListAssignments();

(This bit of code is exactly after InitializeCompenent() is called) And for the heck of it, I added a sample: (这部分代码恰好在调用InitializeCompenent()之后),为此,我添加了一个示例:

Assignment sample1 = new Assignment()
        {
            Title = "A Test",
            Start = DateTime.Now,
            Due = DateTime.Now,
            Kind = (byte) Kind.Assignment,
            Priority = (byte) Priority.Medium,
        };
        _repo.CreateAssignment(sample1);
        _repo.SaveChanges(); 

(where _repo is my Repository because I am using the repository pattern) When I put this bit of code before I set the ListView's ItemsSource, the sample shows. (其中_repo是我的存储库,因为我使用的是存储库模式)在设置ListView的ItemsSource之前放入这段代码时,该示例将显示。 BUT when this bit of code is anywhere after ItemsSource is set, the sample doesn't show. 但是,如果在设置ItemsSource之后的任何位置都存在此代码,则不会显示该示例。 How can I constantly update the ItemsSource everytime an Assignment is added? 每次添加分配时,如何不断更新ItemsSource?
My IRepository: 我的资料库:

public interface IAssignmentRepository
{
    Assignment CreateAssignment(Assignment assignmentToCreate);
    void DeleteAssignment(Assignment assignmentToDelete);
    Assignment GetAssignment(int id);
    IEnumerable<Assignment> ListAssignments();
    void SaveChanges();
}

I think the reason is that your IAssignmentRepository doesn't implement the INotifyCollectionChanged interface. 我认为原因是您的IAssignmentRepository没有实现INotifyCollectionChanged接口。

When you add the data before setting the ItemsSource, the data is already there for viewing as soon as the GUI updates. 当您在设置ItemsSource之前添加数据时,该数据已经存在,以便在GUI更新后立即查看。 But when you make subsequent changes, since the repository won't notify the databound control, no updates occur. 但是,当您进行后续更改时,由于存储库不会通知数据绑定控件,因此不会发生任何更新。

I'm also assuming that you've set the DataContext properly. 我还假设您已经正确设置了DataContext。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM