From 5c1f1db65bbc5a113de7d8e631adcd35a4480869 Mon Sep 17 00:00:00 2001 From: SKharchi Date: Tue, 11 May 2021 13:21:59 +0200 Subject: [PATCH] See https://github.com/HandyOrg/HandyControl/pull/818 In default, set Window.SizeToContent to Width or Height or WidthAndHeight, when the content size changed, the window will not re-center to screen or owner. After add this attached property, it will auto re-center. --- .../Controls/Attach/WindowAttach.cs | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) 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; + } + } + } } }