diff --git a/src/Shared/HandyControl_Shared/Controls/Attach/WindowAttach.cs b/src/Shared/HandyControl_Shared/Controls/Attach/WindowAttach.cs index f6b2e1938..77c22f240 100644 --- a/src/Shared/HandyControl_Shared/Controls/Attach/WindowAttach.cs +++ b/src/Shared/HandyControl_Shared/Controls/Attach/WindowAttach.cs @@ -145,5 +145,39 @@ public static void SetHideWhenClosing(DependencyObject element, bool value) public static bool GetHideWhenClosing(DependencyObject element) => (bool) element.GetValue(HideWhenClosingProperty); + + public static readonly DependencyProperty KeepCenterOnSizeChangedProperty = + DependencyProperty.RegisterAttached("KeepCenterOnSizeChanged", typeof(bool), typeof(WindowAttach), + new PropertyMetadata(ValueBoxes.FalseBox, KeepCenterOnSizeChangedPropertyChanged)); + + [AttachedPropertyBrowsableForType(typeof(System.Windows.Window))] + [AttachedPropertyBrowsableForType(typeof(Window))] + public static bool GetKeepCenterOnSizeChanged(DependencyObject obj) => (bool) obj.GetValue(KeepCenterOnSizeChangedProperty); + + public static void SetKeepCenterOnSizeChanged(DependencyObject obj, bool value) => obj.SetValue(KeepCenterOnSizeChangedProperty, value); + + private static void KeepCenterOnSizeChangedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + if (d is Window window) + { + if ((bool) e.NewValue) + window.SizeChanged += Window_SizeChanged; + else + window.SizeChanged -= Window_SizeChanged; + } + + static void Window_SizeChanged(object sender, SizeChangedEventArgs e) + { + var window = (Window) sender; + if (window.WindowStartupLocation == WindowStartupLocation.CenterOwner || + window.WindowStartupLocation == WindowStartupLocation.CenterScreen) + { + if (e.WidthChanged) + window.Left += (e.PreviousSize.Width - e.NewSize.Width) / 2; + if (e.HeightChanged) + window.Top += (e.PreviousSize.Height - e.NewSize.Height) / 2; + } + } + } } }