XAML-Map-Control/MapControl/WPF/PolygonCollection.WPF.cs

70 lines
2.3 KiB
C#
Raw Normal View History

2025-02-27 18:46:32 +01:00
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Windows;
namespace MapControl
{
/// <summary>
/// An ObservableCollection of IEnumerable of Location. PolygonCollection adds a CollectionChanged
/// listener to each element that implements INotifyCollectionChanged and, when such an element changes,
/// fires its own CollectionChanged event with NotifyCollectionChangedAction.Replace for that element.
/// </summary>
public class PolygonCollection : ObservableCollection<IEnumerable<Location>>, IWeakEventListener
{
public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, sender, sender));
2024-05-26 12:39:40 +02:00
return true;
}
protected override void InsertItem(int index, IEnumerable<Location> polygon)
{
2024-07-16 21:29:25 +02:00
if (polygon is INotifyCollectionChanged addedPolygon)
{
2024-07-16 21:29:25 +02:00
CollectionChangedEventManager.AddListener(addedPolygon, this);
}
base.InsertItem(index, polygon);
}
protected override void SetItem(int index, IEnumerable<Location> polygon)
{
2024-07-16 21:29:25 +02:00
if (this[index] is INotifyCollectionChanged removedPolygon)
{
2024-07-16 21:29:25 +02:00
CollectionChangedEventManager.RemoveListener(removedPolygon, this);
}
if (polygon is INotifyCollectionChanged addedPolygon)
{
CollectionChangedEventManager.AddListener(addedPolygon, this);
}
base.SetItem(index, polygon);
}
protected override void RemoveItem(int index)
{
2024-07-16 21:29:25 +02:00
if (this[index] is INotifyCollectionChanged removedPolygon)
{
2024-07-16 21:29:25 +02:00
CollectionChangedEventManager.RemoveListener(removedPolygon, this);
}
base.RemoveItem(index);
}
protected override void ClearItems()
{
2024-07-16 21:29:25 +02:00
foreach (var polygon in this.OfType<INotifyCollectionChanged>())
{
2024-07-16 21:29:25 +02:00
CollectionChangedEventManager.RemoveListener(polygon, this);
}
base.ClearItems();
}
}
}