How do I bind a command to e.g. the right mouse button in a ControlTemplate in WPF?
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. Bindi开发者_如何转开发ng 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
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.
精彩评论