WPF - 如何扩展(或并行工作)内置命令机制?

发布于 2024-08-18 14:34:56 字数 767 浏览 1 评论 0原文

如果这是一个愚蠢的问题,请原谅我 - 我已经阅读了十几篇有关 WPF 命令基础结构的文章,但我比以往任何时候都更加困惑。

我知道我可以使用内置命令来实现(例如)一个工具栏,该工具栏将标准剪切/复制/粘贴功能应用于任何聚焦的文本框:

<ToolBar>
    <Button Command="{x:Static ApplicationCommands.Cut}">Cut</Button>
    <Button Command="{x:Static ApplicationCommands.Copy}">Copy</Button>
    <Button Command="{x:Static ApplicationCommands.Paste}">Paste</Button>
</ToolBar>

但我想扩展此模式,以便可以使用单个工具栏对一系列不同的控件调用类似(但不相同)的操作。例如,我可能会创建一个派生自 ListBox 的自定义控件,该控件还支持剪切、复制和粘贴操作。尽管在 ListBox 上执行复制操作的代码与在 TextBox 上执行复制操作的代码不同,但仍会从同一工具栏按钮调用它。

所以,我的问题是:

[1] 需要在自定义控件中实现什么,才能像上面的示例一样进行命令?具体来说,当聚焦时应该可以从工具栏中发现它。

[2] 工具栏中需要什么标记才能允许单个按钮根据所聚焦的控件类型调用不同的命令?

非常感谢您提供的任何建议。

蒂姆

Please excuse me if this is a dumb question - I have read a dozen articles on the WPF command infrastructure and I am more confused than ever.

I understand that I can use the built-in commands to implement (for example) a toolbar that will apply standard cut/copy/paste functionality to any focused textbox:

<ToolBar>
    <Button Command="{x:Static ApplicationCommands.Cut}">Cut</Button>
    <Button Command="{x:Static ApplicationCommands.Copy}">Copy</Button>
    <Button Command="{x:Static ApplicationCommands.Paste}">Paste</Button>
</ToolBar>

But I want to extend this pattern so that a single toolbar can be used to invoke similar (but not identical) operations on a range of different controls. For example, I might create a custom control that derives from ListBox, that also supports cut, copy and paste operations. Although the execution of a copy operation on a ListBox will be coded differently to that of a TextBox, it would still be invoked from the same toolbar button.

So, my questions are:

[1] What needs to be implemented in a custom control in order that it can be commanded as in the above example? Specifically, it should be discoverable from a toolbar when focused.

[2] What markup is required in the toolbar to allow a single button to invoke different commands, depending on the type of control that is focused?

Many thanks for any advice you can offer.

Tim

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

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

发布评论

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

评论(1

妄想挽回 2024-08-25 14:34:56

具有 MVVM 模式的通用 RelayCommands 是创建 WPF 应用程序的最佳方法。您可以在此处阅读相关内容。通过将数据上下文指定为命令的存在类,可以将这些命令绑定到任何控件。

标记将仅使用 Binding 关键字而不是 x:Static。

如果这能解决您的疑问,请告诉我。

苏尚特。

Generic RelayCommands with MVVM Pattern are the best way to create a WPF Application. You can read about it here. These commands can be binded to any control by specifying the datacontext as the class of existence of the commands.

The markup would just use Binding keyword instead of x:Static.

Let me know if this solves your query.

Sushant.

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