Created
August 3, 2022 04:08
-
-
Save emoacht/c58e85f0b6e54247af56f22f3959fb93 to your computer and use it in GitHub Desktop.
Drag window without title bar by mouse left button down.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class WindowHelper | |
{ | |
public static bool GetIsDragEnabled(DependencyObject obj) | |
{ | |
return (bool)obj.GetValue(IsDragEnabledProperty); | |
} | |
public static void SetIsDragEnabled(DependencyObject obj, bool value) | |
{ | |
obj.SetValue(IsDragEnabledProperty, value); | |
} | |
public static readonly DependencyProperty IsDragEnabledProperty = | |
DependencyProperty.RegisterAttached("IsDragEnabled", typeof(bool), typeof(WindowHelper), new PropertyMetadata(false, OnChanged)); | |
private static void OnChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) | |
{ | |
var window = d as Window ?? Window.GetWindow(d); | |
if (window is null) | |
return; | |
if ((bool)e.NewValue) | |
{ | |
window.PreviewMouseLeftButtonDown += OnPreviewMouseLeftButtonDown; | |
window.Closed += OnClosed; | |
} | |
else | |
{ | |
window.PreviewMouseLeftButtonDown -= OnPreviewMouseLeftButtonDown; | |
window.Closed -= OnClosed; | |
} | |
static void OnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) | |
{ | |
// Make sure left button is pressed. | |
if (Mouse.LeftButton == MouseButtonState.Pressed) | |
((Window)sender).DragMove(); | |
} | |
static void OnClosed(object? sender, EventArgs e) | |
{ | |
if (sender is Window window) | |
{ | |
window.PreviewMouseLeftButtonDown -= OnPreviewMouseLeftButtonDown; | |
window.Closed -= OnClosed; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment