不断更新ListView的ItemsSource?
我有一个 ListView,我将其 ItemsSource 设置为列出所有分配(我的 SQL 数据库中的一个表,ORM 是 LINQ to SQL),如下所示:(
ltvAssignments.ItemsSource = _repo.ListAssignments();
这段代码恰好在调用 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();
其中 _repo 是我的存储库,因为我正在使用存储库模式)当我在设置 ListView 的 ItemsSource 之前放置这段代码时,示例会显示。但是,当这段代码位于设置 ItemsSource 之后的任何位置时,示例不会显示。如何在每次添加作业时不断更新 ItemsSource?
我的存储库:
public interface IAssignmentRepository
{
Assignment CreateAssignment(Assignment assignmentToCreate);
void DeleteAssignment(Assignment assignmentToDelete);
Assignment GetAssignment(int id);
IEnumerable<Assignment> ListAssignments();
void SaveChanges();
}
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:
ltvAssignments.ItemsSource = _repo.ListAssignments();
(This bit of code is exactly after InitializeCompenent() is called) And for the heck of it, I added a sample:
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. BUT when this bit of code is anywhere after ItemsSource is set, the sample doesn't show. How can I constantly update the ItemsSource everytime an Assignment is added?
My IRepository:
public interface IAssignmentRepository
{
Assignment CreateAssignment(Assignment assignmentToCreate);
void DeleteAssignment(Assignment assignmentToDelete);
Assignment GetAssignment(int id);
IEnumerable<Assignment> ListAssignments();
void SaveChanges();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为原因是您的 IAssignmentRepository 没有实现 INotifyCollectionChanged 接口。
当您在设置 ItemsSource 之前添加数据时,一旦 GUI 更新,数据就已经存在,可供查看。但是,当您进行后续更改时,由于存储库不会通知数据绑定控件,因此不会发生更新。
我还假设您已正确设置 DataContext。
I think the reason is that your IAssignmentRepository doesn't implement the INotifyCollectionChanged interface.
When you add the data before setting the ItemsSource, the data is already there for viewing as soon as the GUI updates. 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.