鼠标事件处理实现简单的拖放功能。

在实现拖放功能中,分为三个步骤:

1.按下鼠标,触发 MouseLeftButtonDown 事件,选择要拖动的对象。

2.移动鼠标,触发 MouseMove 事件,移动选择的对象。

3.放开鼠标,触发 MouseLeftButtonUp 事件,停止捕捉事件。

但是在实际运行过程中,只能触发MouseMove事件,不能触发MouseLeftButtonDown和MouseLeftButtonUp事件。经过查阅资料,发现这跟路由顺序有关,控件在捕获了MouseLeftButtonDown或MouseLeftButtonUp事件后,会将该事件的"Handled"设置为true,这个属性是用在路由事件中的,当某个控件得到一个RoutedEvent,就会检测Handled是否为true,为true则忽略该事件。并且,控件本身的Click事件,相当于将MouseLeftButtonDown和MouseLeftButtonUp事件抑制掉了,转换成了Click事件。

解决方案一(部分解决问题):

设置Button的ClickMode 属性:

属性
但是此方法并不能完全解决问题,能达到触发事件的目的,但是不能实现所需的拖放功能。

解决方案二(完美解决问题):

在初始化的函数里利用UIElement的AddHandler方法,显式的增加这个事件。

方法说明:

UIElement.AddHandler方法 (RoutedEvent, Delegate, Boolean)

为指定的路由事件添加路由事件处理程序,并将该处理程序添加到当前元素的处理程序集合中。将 handledEventsToo 指定为 true 时,可为已标记为由其他元素在事件路由过程中处理的路由事件调用所提供的处理程序。

初始化函数里面添加的代码:

bt1.AddHandler(Button.MouseLeftButtonDownEvent, new MouseButtonEventHandler(this.Button_MouseLeftButtonDown), true);
        bt1.AddHandler(Button.MouseLeftButtonUpEvent, new MouseButtonEventHandler(this.Button_MouseLeftButtonUp), true);

按钮名称.AddHandler(Button.MouseLeftButtonUpEvent, new MouseButtonEventHandler(this.按钮名称_MouseLeftButtonUp), true);

http://t.zoukankan.com/junyuz-p-1921672.html
本文至此结束
最后修改:2022 年 06 月 10 日
如果觉得我的文章对你有用,请随意赞赏