Make WPF window draggable, no matter what element is clicked

Alex K picture Alex K · Sep 14, 2011 · Viewed 87.2k times · Source

My question is 2 fold, and I am hoping there are easier solutions to both provided by WPF rather than the standard solutions from WinForms (which Christophe Geers provided, before I've made this clarification).

First, is there a way to make Window draggable without capturing and processing mouse-click+drag events? I mean the window is draggable by the title bar, but if I set a window not to have one and still want to be able to drag it, is there a way to just re-direct the events somehow to whatever handles the title bar dragging?

Second, is there a way to apply an event handler to all elements in the window? As in, make the window draggable no matter which element the user click+drags. Obviously without adding the handler manually, to every single element. Just do it once somewhere?

Answer

Rachel picture Rachel · Sep 14, 2011

Sure, apply the following MouseDown event of your Window

private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
    if (e.ChangedButton == MouseButton.Left)
        this.DragMove();
}

This will allow users to drag the Window when they click/drag on any control, EXCEPT for controls which eat the MouseDown event (e.Handled = true)

You can use PreviewMouseDown instead of MouseDown, but the drag event eats the Click event, so your window stops responding to left-mouse click events. If you REALLY wanted to be able to click and drag the form from any control, you could probably use PreviewMouseDown, start a timer to begin the drag operation, and cancel the operation if the MouseUp event fires within X milliseconds.