WPF如何实现支持MouseLeftButtonDown/Up冒泡且符合MVVM规范的Button控件
问题根因
WPF原生Button控件的内部逻辑会将MouseLeftButtonDown和MouseLeftButtonUp路由事件的Handled属性标记为True,冒泡路由到Button层级后就停止传播,因此你绑定的冒泡路由事件触发器无法捕获到对应事件。
最简实现方案
直接将触发器绑定到隧道路由版本的鼠标事件即可,隧道路由事件在元素内部处理逻辑之前触发,不会被Handled标记阻断,完全不需要修改控件、也不需要写后置代码,符合MVVM要求:
<Button Width="30" Height="20" Content="+"> <i:Interaction.Triggers> <i:EventTrigger EventName="PreviewMouseLeftButtonDown"> <i:InvokeCommandAction Command="{Binding MoveAxisFwdCommand}" CommandParameter="true" /> </i:EventTrigger> <i:EventTrigger EventName="PreviewMouseLeftButtonUp"> <i:InvokeCommandAction Command="{Binding MoveAxisFwdCommand}" CommandParameter="false" /> </i:EventTrigger> </i:Interaction.Triggers> </Button>
兼容性说明
该方案完全保留Button的全部原生功能,包括点击动效、原生Command绑定、IsEnabled状态管控等逻辑,不会产生额外副作用。
内容的提问来源于stack exchange,提问作者piter123
相关产品推荐
相关产品推荐

