[英]ObservableCollection<DateTime> and updating the UI when the item changes
[英]UI only updating once when adding new item to ObservableCollection
一小時前我遇到了一個非常奇怪的錯誤,但無法解決。 我的代碼包含一個綁定到我的視圖(列表視圖)的 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"
});
}
}
}
}
嘗試添加NotifyPropertyChanged("Departments");
添加新項目之后,例如之后
_Departments.Add(
new DepartmentEntity()
{
Id = DepartmentId,
Department = "Bitte ändern"
});
它允許 UI 了解Departments
屬性已更新。 您還可以考慮在Departments
getter 中刪除此代碼
var container = ContainerConfig.Configure();
using (var scope = container.BeginLifetimeScope())
{
var test = scope.Resolve<IDepartmentRepository>();
_Departments = test.GetAll().ToObservable();
}
因為您已經將新項目添加到_Departments
支持字段
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.