将WPF的内置路由命令与Caliburn一起使用的最佳方法是什么?
例如,在我的shell中,我有一个编辑菜单,其中的复制项目附加到ApplicationCommands
中的标准命令:
<Menu>
<MenuItem Header="Edit">
<MenuItem Header="Copy"
Command="ApplicationCommands.Copy" />
</MenuItem>
</Menu>
我希望此项目在有焦点时由TextBox
处理,在有焦点时由我自己的控件处理。在我的控件中,我可以通过创建Execute
来处理代码中的CanExecute
和CommandBinding
:
<UserControl.CommandBindings>
<CommandBinding Command="ApplicationCommands.Copy"
Executed="CopyCommandExecute"
CanExecute="CanCopyCommandExecute" />
</UserControl.CommandBindings>
有没有办法,使用Caliburn来处理我的ViewModel中的方法,或者重定向到我从ViewModel公开的另一个命令?或者我是以错误的方式解决这个问题?
答案 0 :(得分:1)
我最终创建了a behaviour,允许将剪贴板RoutedCommands重定向到其他命令。
public class ClipboardBehavior : Behavior<Control>
{
public static readonly DependencyProperty CopyCommandProperty =
DependencyProperty.Register("CopyCommand",
typeof (ICommand),
typeof (ClipboardBehavior),
new PropertyMetadata(default(ICommand)));
public static readonly DependencyProperty CutCommandProperty =
DependencyProperty.Register("CutCommand",
typeof (ICommand),
typeof (ClipboardBehavior),
new PropertyMetadata(default(ICommand)));
public static readonly DependencyProperty DeleteCommandProperty =
DependencyProperty.Register("DeleteCommand",
typeof (ICommand),
typeof (ClipboardBehavior),
new PropertyMetadata(default(ICommand)));
public static readonly DependencyProperty PasteCommandProperty =
DependencyProperty.Register("PasteCommand",
typeof (ICommand),
typeof (ClipboardBehavior),
new PropertyMetadata(default(ICommand)));
public ICommand DeleteCommand
{
get { return (ICommand) GetValue(DeleteCommandProperty); }
set { SetValue(DeleteCommandProperty, value); }
}
public ICommand CutCommand
{
get { return (ICommand) GetValue(CutCommandProperty); }
set { SetValue(CutCommandProperty, value); }
}
public ICommand CopyCommand
{
get { return (ICommand) GetValue(CopyCommandProperty); }
set { SetValue(CopyCommandProperty, value); }
}
public ICommand PasteCommand
{
get { return (ICommand) GetValue(PasteCommandProperty); }
set { SetValue(PasteCommandProperty, value); }
}
protected override void OnAttached()
{
AddBinding(ApplicationCommands.Delete, () => DeleteCommand);
AddBinding(ApplicationCommands.Cut, () => CutCommand);
AddBinding(ApplicationCommands.Copy, () => CopyCommand);
AddBinding(ApplicationCommands.Paste, () => PasteCommand);
}
private void AddBinding(ICommand command, Func<ICommand> executingCommand)
{
var binding = new CommandBinding(command,
(sender, e) => Execute(e, executingCommand()),
(sender, e) => CanExecute(e, executingCommand()));
AssociatedObject.CommandBindings.Add(binding);
}
private static void CanExecute(CanExecuteRoutedEventArgs args, ICommand command)
{
if (command != null)
{
args.CanExecute = command.CanExecute(args.Parameter);
args.ContinueRouting = false;
}
}
private static void Execute(ExecutedRoutedEventArgs e, ICommand command)
{
if (command != null)
command.Execute(e.Parameter);
}
}