具有多种目标类型的 WPF 命令
我对具有不同目标类型的 WPF 命令有点困惑。
因此,如果我定义一个命令
<Window.CommandBindings>
<CommandBinding Command="Copy"
Executed="CopyCmdExecuted"
CanExecute="CopyCmdCanExecute"/>
</Window.CommandBindings>
现在我在上下文菜单中使用它:
<ContextMenu Name="FolderContextMenu">
<MenuItem Command="Copy"/>
</ContextMenu>
我有一个方法来处理该命令:
private void CopyCmdExecuted(object sender, ExecutedRoutedEventArgs e)
{
}
我在一个普通的旧菜单中使用它:
<Menu Name="editMenu">
<MenuItem Command="Copy"/>
</Menu>
我理解这一点没有问题。但我有点困惑,如果目标对象是不同类型,我应该做什么。
假设我有文件夹和用户,它们都有一个带有“新建”命令的上下文菜单(以及菜单栏编辑菜单,其中也有“新建”命令)。
当执行New时,无论是Folder还是User,都会执行CopyCmdExecuted。那么,我现在应该对目标进行多路分解吗?就像
private void CopyCmdExecuted(object sender, ExecutedRoutedEventArgs e)
{
if(sender is User)
// Do copy user stuff
if(sender is Folder)
// Do copy folder stuff
}
如果我最终想要复制很多数据类型,这似乎有点烦人。我在这里不明白什么吗?
(显然,我可以使用 DoCopy 从 Copiable 基类继承文件夹和用户,但这似乎仍然是错误的。)
I'm a bit confused about WPF commands with different target types.
So if I define a command
<Window.CommandBindings>
<CommandBinding Command="Copy"
Executed="CopyCmdExecuted"
CanExecute="CopyCmdCanExecute"/>
</Window.CommandBindings>
And now I use it in a context menu:
<ContextMenu Name="FolderContextMenu">
<MenuItem Command="Copy"/>
</ContextMenu>
And I have a method to handle the command:
private void CopyCmdExecuted(object sender, ExecutedRoutedEventArgs e)
{
}
And I use it in a plain old menu:
<Menu Name="editMenu">
<MenuItem Command="Copy"/>
</Menu>
I have no problem understanding that. But I'm a bit confused what I am supposed to do if the target objects are different types.
Lets say I have Folders and Users, both of which have a context menu with the New command (and the menu bar edit menu which also has the New command).
When New is executed, regardless of whether its a Folder or a User, CopyCmdExecuted is executed. So, am I now supposed to de-multiplex on the target? Something like
private void CopyCmdExecuted(object sender, ExecutedRoutedEventArgs e)
{
if(sender is User)
// Do copy user stuff
if(sender is Folder)
// Do copy folder stuff
}
If I end up with lots of data types I wish to copy, it seems a bit annoying. Am I not understanding something here?
(Obviously, I could just have Folder and User inherit from a Copiable base class with DoCopy but that still seems wrong.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在调用
Command
时发送CommandParameter
来指示要应用的命令的含义。这里有两个TextBlock
元素:并且此代码隐藏:
使用参数来确定上下文菜单适用于哪个
TextBlock
。如果适合您,您也可以只使用字符串"File"
和"Folder"
。You can send a
CommandParameter
when you invoke theCommand
to indicate what you mean the command to apply to. Here's are twoTextBlock
elements:and this code-behind:
uses the parameter to figure out which
TextBlock
the context menu applies to. You can also just use the strings"File"
and"Folder"
if that works for you.