【发布时间】:2019-10-20 20:22:52
【问题描述】:
一个小时前我遇到了一个非常奇怪的错误,但无法解决。我的代码包含一个绑定到我的视图(列表视图)的 ObservableCollection。我可以在我的数据库中添加一个新项目,它也会被添加到我的 ObservableCollection 中。 UI 正在正确更新,但只是第一次。如果我添加第二个项目,它将出现在我的数据库和我的集合中,但我的 UI 不再更新。谁能检查我的代码看看是否有问题?
查看:
<ListView Name="Departments_Listview" ItemsSource="{Binding Departments, UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding YourSelectedItem, Mode=TwoWay}" Height="346">
<ListView.View>
<GridView>
<GridViewColumn Header="Department" DisplayMemberBinding="{Binding Department}"/>
</GridView>
</ListView.View>
</ListView>
视图模型
using Autofac;
using Calendar.Commands;
using Calendar.Database.Entities;
using Calendar.Database.Repositories;
using Calendar.Helper_Classes;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Windows;
namespace Calendar.ViewModels
{
public class DepartmentViewModel : ViewModelBase
{
private RelayCommand command;
private DepartmentEntity _yourSelectedItem;
ObservableCollection<DepartmentEntity> _Departments = new ObservableCollection<DepartmentEntity>();
public DepartmentViewModel()
{
}
public ObservableCollection<DepartmentEntity> Departments
{
get
{
var container = ContainerConfig.Configure();
using (var scope = container.BeginLifetimeScope())
{
var test = scope.Resolve<IDepartmentRepository>();
_Departments = test.GetAll().ToObservable();
}
return _Departments;
}
set
{
_Departments = value;
NotifyPropertyChanged("Departments");
}
}
private string department;
public string Department
{
get { return department; }
set
{
department = value;
NotifyPropertyChanged("Department");
}
}
public DepartmentEntity YourSelectedItem
{
get
{
return _yourSelectedItem;
}
set
{
if (value != null)
{
Department = value.Department;
}
_yourSelectedItem = value;
NotifyPropertyChanged("YourSelectedItem");
}
}
private void NewDepartment()
{
var container = ContainerConfig.Configure();
using (var scope = container.BeginLifetimeScope())
{
var NewDepartment = scope.Resolve<IDepartmentRepository>();
DepartmentEntity newDepartment = new DepartmentEntity
{
Department = "Bitte ändern"
};
NewDepartment.Add(newDepartment);
int DepartmentId = NewDepartment.Count();
_Departments.Add(
new DepartmentEntity()
{
Id = DepartmentId,
Department = "Bitte ändern"
});
}
}
}
}
【问题讨论】: