如何将命令绑定到 WPF 中 ControlTemplate 中的鼠标右键等?

发布于 2024-09-04 16:27:04 字数 231 浏览 1 评论 0原文

我有一个自定义 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

神魇的王 2024-09-11 16:27:04

涉及 MouseGesture,但您不必显式构造它。您可以使用 MouseBinding ,它会在后台为您构造一个 MouseGesture

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

 <ControlTemplate ...>
   <Decorator>

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

     ... content here ...

   </Decorator>
 </ControlTemplate>

您的 ControlTemplate 更有可能使用诸如 DockPanel 或 Grid 之类的面板进行布局,在这种情况下,您可以将绑定附加到该面板,而不是添加装饰器。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文