Just a quick post this time: I had a need to be able to reposition a WPF window when I click and dragged on a particular UIElement. The aim was to recreate the behaviour of clicking and dragging on a standard Windows title bar (in my case, I was implementing my own title bar).

It turns out this is very easy to achieve, so I wrapped the functionality up in a simple WPF behaviour. You can simply attach this behaviour to any on-screen element, and it will automatically find the parent window, and hook everything up.

///     Attach this behaviour to any framework element to allow the entire parent window to be moved
///     when you click and drag this element.
/// </summary>
public class DragWindowBehaviour : Behavior<FrameworkElement>
{
    private Window _parentWindow;

    protected override void OnAttached()
    {
        _parentWindow = GetParentWindow(AssociatedObject);
        if (_parentWindow == null) return;
        AssociatedObject.PreviewMouseLeftButtonDown += _associatedObject_MouseLeftButtonDown;
    }

    private void _associatedObject_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        _parentWindow.DragMove();
    }

    private static Window GetParentWindow(DependencyObject attachedElement)
    {
        return attachedElement.TryFindParent<Window>();
    }

    protected override void OnDetaching()
    {
        AssociatedObject.PreviewMouseLeftButtonDown -= _associatedObject_MouseLeftButtonDown;
        _parentWindow = null;
    }
}

As I said, it’s simple code. The key part is the _parentWindow.DragMove() call, which effectively hands over the drag operation to the Window control.

Hopefully someone will find this useful 🙂

Categories: C#WPF

1 Comment

Mike Pelley · 2 October 2016 at 11:44 pm

This was very helpful, thanks! One note: TryFindParent() doesn’t seem to be available from DependencyObject, so I used Window.GetWindow(attachedElement).

For those who are new to behaviors like me, you can attach this to an element by placing this inside:

Leave a Reply

Avatar placeholder

Your email address will not be published.