使 WPF 窗口可拖动,无论单击什么元素 [英] Make WPF window draggable, no matter what element is clicked

查看:55
本文介绍了使 WPF 窗口可拖动,无论单击什么元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是 2 倍,我希望 WPF 提供更简单的解决方案,而不是 WinForms 的标准解决方案(在我做出此澄清之前由 Christophe Geers 提供).

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).

首先,有没有办法在不捕获和处理鼠标单击+拖动事件的情况下使Window可拖动?我的意思是窗口可以通过标题栏拖动,但是如果我将窗口设置为没有窗口并且仍然希望能够拖动它,有没有办法以某种方式将事件重新定向到处理标题栏拖动的任何内容?

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?

推荐答案

当然,应用您的 Window

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

这将允许用户在任何控件上单击/拖动时拖动窗口,除了吃 MouseDown 事件的控件 (e.Handled = true)

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)

您可以使用 PreviewMouseDown 而不是 MouseDown,但拖动事件会吃掉 Click 事件,因此您的窗口停止响应鼠标左键单击事件.如果您真的希望能够从任何控件单击并拖动表单,您可以使用 PreviewMouseDown,启动一个计时器开始拖动操作,如果 MouseUp 事件在 X 毫秒内触发.

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.

这篇关于使 WPF 窗口可拖动,无论单击什么元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆