Reputation: 123
I want to notify parent ReportModel
when Technicians
CollectionChanged. It works when creationg new ReportModel
, but when I'm starting editing ReportModel
from DB, ObservableCollection is created via HasConversion extension and CollectionChanged isn't fired anymore.
Any doubts how to achieve it?
public class ReportModel : ModelBase, IModel
{
private ObservableCollection<ReportPerson> technicians = new();
public ReportModel()
{
Technicians.CollectionChanged += Technicians_CollectionChanged;
}
private void Technicians_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (var item in e.NewItems)
{
if (item is INotifyPropertyChanged notifyPropertyChanged)
notifyPropertyChanged.PropertyChanged += TechNotifyPropertyChanged_PropertyChanged;
}
}
if (e.OldItems != null)
{
foreach (var item in e.OldItems)
{
if (item is INotifyPropertyChanged notifyPropertyChanged)
notifyPropertyChanged.PropertyChanged -= TechNotifyPropertyChanged_PropertyChanged;
}
}
OnPropertyChanged(nameof(Technicians));
}
private void TechNotifyPropertyChanged_PropertyChanged(object? sender, PropertyChangedEventArgs e) => OnPropertyChanged(nameof(Technicians));
[Column(name: "technicians", Order = 50)]
public ObservableCollection<ReportPerson> Technicians
{
get => technicians;
set
{
if (technicians != value)
{
if (technicians != null)
{
technicians.CollectionChanged -= Technicians_CollectionChanged;
foreach (var tech in technicians)
{
if (tech is INotifyPropertyChanged notifyPropertyChanged)
{
notifyPropertyChanged.PropertyChanged -= TechNotifyPropertyChanged_PropertyChanged;
}
}
}
technicians = value;
if (technicians != null)
{
technicians.CollectionChanged += Technicians_CollectionChanged;
foreach (var tech in technicians)
{
if (tech is INotifyPropertyChanged notifyPropertyChanged)
{
notifyPropertyChanged.PropertyChanged += TechNotifyPropertyChanged_PropertyChanged;
}
}
}
OnPropertyChanged(nameof(Technicians));
}
}
}
}
modelBuilder.Entity<ReportModel>().Property(c => c.Technicians).HasConversion(
v => JsonSerializer.Serialize(v, (JsonSerializerOptions)null),
v => JsonSerializer.Deserialize<ObservableCollection<ReportPerson>>(v, (JsonSerializerOptions)null));
Upvotes: 0
Views: 32