How do I bind a command to e.g. the right mouse button in a ControlTemplate in WPF?

巧了我就是萌 提交于 2019-12-13 19:24:00

问题


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.


回答1:


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.

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>

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.



来源:https://stackoverflow.com/questions/2976169/how-do-i-bind-a-command-to-e-g-the-right-mouse-button-in-a-controltemplate-in-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!