using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Windows; using System.Windows.Media; using System.Windows.Shapes; namespace XP.ImageProcessing.RoiControl { /// /// 多边形Points附加行为,支持ObservableCollection绑定 /// public static class PolygonPointsBehavior { private static readonly Dictionary> _attachedCollections = new Dictionary>(); public static ObservableCollection GetPointsSource(DependencyObject obj) { return (ObservableCollection)obj.GetValue(PointsSourceProperty); } public static void SetPointsSource(DependencyObject obj, ObservableCollection value) { obj.SetValue(PointsSourceProperty, value); } public static readonly DependencyProperty PointsSourceProperty = DependencyProperty.RegisterAttached( "PointsSource", typeof(ObservableCollection), typeof(PolygonPointsBehavior), new PropertyMetadata(null, OnPointsSourceChanged)); private static void OnPointsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (!(d is Polygon polygon)) return; // 清理旧的订阅 if (e.OldValue is ObservableCollection oldCollection) { oldCollection.CollectionChanged -= GetCollectionChangedHandler(polygon); _attachedCollections.Remove(polygon); } // 设置新的订阅 if (e.NewValue is ObservableCollection newCollection) { // 初始化Points UpdatePolygonPoints(polygon, newCollection); // 监听集合变化 NotifyCollectionChangedEventHandler handler = (s, args) => UpdatePolygonPoints(polygon, newCollection); newCollection.CollectionChanged += handler; // 保存引用以便后续清理 _attachedCollections[polygon] = newCollection; // 监听Polygon卸载事件以清理资�? polygon.Unloaded += (s, args) => { if (_attachedCollections.TryGetValue(polygon, out var collection)) { collection.CollectionChanged -= handler; _attachedCollections.Remove(polygon); } }; } } private static NotifyCollectionChangedEventHandler GetCollectionChangedHandler(Polygon polygon) { return (s, args) => { if (s is ObservableCollection collection) { UpdatePolygonPoints(polygon, collection); } }; } private static void UpdatePolygonPoints(Polygon polygon, ObservableCollection points) { // 使用Dispatcher确保在UI线程更新 polygon.Dispatcher.BeginInvoke(new Action(() => { // 创建新的PointCollection以触发UI更新 polygon.Points = new PointCollection(points); }), System.Windows.Threading.DispatcherPriority.Render); } } }