Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
SamXion committed May 11, 2021
1 parent 809386a commit 5c1f1db
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/Shared/HandyControl_Shared/Controls/Attach/WindowAttach.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
}
}
}

0 comments on commit 5c1f1db

Please sign in to comment.