using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace Azaion.Annotator.Extensions; public static class CanvasExtensions { public static readonly DependencyProperty PercentPositionProperty = DependencyProperty.RegisterAttached("PercentPosition", typeof(Point), typeof(CanvasExtensions), new PropertyMetadata(new Point(0, 0), OnPercentPositionChanged)); public static readonly DependencyProperty PercentSizeProperty = DependencyProperty.RegisterAttached("PercentSize", typeof(Point), typeof(CanvasExtensions), new PropertyMetadata(new Point(0, 0), OnPercentSizeChanged)); private static void OnPercentSizeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { } public static void SetPercentPosition(DependencyObject obj, Point value) => obj.SetValue(PercentPositionProperty, value); private static void OnPercentPositionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (!(d is FrameworkElement element)) return; if (!(VisualTreeHelper.GetParent(element) is Canvas canvas)) return; canvas.SizeChanged += (s, arg) => { var percentPosition = (Point)element.GetValue(PercentPositionProperty); var xPosition = percentPosition.X * canvas.ActualWidth - element.ActualWidth / 2; var yPosition = percentPosition.Y * canvas.ActualHeight - element.ActualHeight / 2; Canvas.SetLeft(element, xPosition); Canvas.SetTop(element, yPosition); }; } }