ControlTemplate中的鼠标右键

ControlTemplate中的鼠标右键

本文介绍了如何将命令绑定到WPF中ControlTemplate中的鼠标右键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义Control派生类和一个视图模型。用户可以使用此控件执行几个操作,我认为最好在视图模型中实现这些作为RoutedCommand对象或ICommand派生对象,以便ControlTemplates可以绑定到它们。将命令绑定到一个ControlTemplate中的按钮应该很简单,但是如何将命令绑定到例如。在另一个ControlTemplate中的鼠标右键?

I have a custom Control derived class and a view model to go with. The user can do several actions with this control, and I'm thinking it's best to implement these as RoutedCommand objects or ICommand derived objects in the view model so the ControlTemplates can bind to them. Binding a command to a button in one ControlTemplate should be straightforward, but how can I bind the command to e.g. the right mouse button in another ControlTemplate? Probably a MouseGesture is involved, but I'm having a hard time fitting the pieces together.

推荐答案

A MouseGesture 涉及,但不必显式构造它。您可以使用 MouseBinding ,它将为您创建 MouseGesture

A MouseGesture is involved, but you don't have to explicitly construct it. You can use a MouseBinding which will construct a MouseGesture for you under the hood.

您需要一个UIElement来附加您的绑定。以下是使用单独装饰器的方法。

You need a UIElement to attach your binding to. Here is how you would do it with a separate decorator.

 <ControlTemplate ...>
   <Decorator>

     <Decorator.InputBindings>
       <MouseBinding MouseAction="RightClick" Command="..." />
     </Decorator.InputBindings>

     ... content here ...

   </Decorator>
 </ControlTemplate>

更可能的是,你的ControlTemplate使用一个面板,如DockPanel或Grid来布局,在这种情况下,将绑定附加到它,而不是添加Decorator。

More likely your ControlTemplate uses a Panel such as a DockPanel or Grid for layout, in which case you could attach the binding to that instead of adding a Decorator.

这篇关于如何将命令绑定到WPF中ControlTemplate中的鼠标右键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 17:47