在XAML中设置命令目标

我很难理解RoutedCommand的CommandTarget属性。

基本上,我有一些静态命令,在用户控件(而不是窗口)中有实现。 我在用户控件中创建了一个命令绑定。 如果我在usercontrol中声明按钮,那么我可以使用我的路由事件。 但是,当按钮位于usercontrol之外时,我无法使用我的路由事件。 我认为命令目标将解决我的问题。

那么如何为工具栏usercontrol的按钮设置commandtarget,以便调用Container的Executed和CanExecuted?

编辑代码与micahtan更改的更改,但我仍然无法得到CanExecute或Execute。

窗口XAML:

      

工具栏XAML:

   

工具栏CS:

  public partial class Toolbar : UserControl { public Toolbar() { InitializeComponent(); } // Using a DependencyProperty as the backing store for CommandTarget. This enables animation, styling, binding, etc... public static readonly DependencyProperty CommandTargetProperty = DependencyProperty.Register("CommandTarget", typeof(IInputElement), typeof(Toolbar), new UIPropertyMetadata(null)); public IInputElement CommandTarget { get { return (IInputElement)GetValue(CommandTargetProperty); } set { SetValue(CommandTargetProperty, value); } } } 

容器XAML:

      

集装箱CS:

 public partial class Container : UserControl { public Container() { InitializeComponent(); } private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) { Console.WriteLine("My Command Executed"); } private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e) { Console.WriteLine("My Command Can Execute"); e.CanExecute = true; } } 

RoutedCommands:

 namespace RoutedCommands { public static class Commands { public static readonly RoutedUICommand MyCommand = new RoutedUICommand(); } } 

如果你想使用CommandTargets,我会在你的自定义UserControl上创建一个CommandTarget DependencyProperty,类似于它在ButtonBase上定义的方式。

完成后,将Button的CommandTarget设置为自定义UserControl的CommandTarget。

编辑:代码示例

如果您正在进行MVVM架构,Rudi的注释是有效的 – 在这种情况下,RelayCommands或其他forms的包装代理工作得很好。 根据您的代码示例,它看起来并不像您使用的那种方法,因此我的原始评论。

至于代码,您只需要更改ToolBar类。 这假设您的MyCommand类inheritance自RoutedUICommand。 这是XAML:

      

这是代码隐藏的代码:

使用System.Windows; 使用System.Windows.Controls;

 namespace WPFCommandTarget { ///  /// Interaction logic for CustomToolBar.xaml ///  public partial class CustomToolBar : UserControl { public CustomToolBar() { InitializeComponent(); } public IInputElement CommandTarget { get { return (IInputElement)GetValue(CommandTargetProperty); } set { SetValue(CommandTargetProperty, value); } } // Using a DependencyProperty as the backing store for CommandTarget. This enables animation, styling, binding, etc... public static readonly DependencyProperty CommandTargetProperty = DependencyProperty.Register("CommandTarget", typeof(IInputElement), typeof(CustomToolBar), new UIPropertyMetadata(null)); } } 

请注意,我已经更改了测试项目中的一些类名/命名空间。 你必须改变它们以满足你的需要。

你有没有想过要使用RelayCommand或DelegateCommand! 你可能更适合你需要的东西?

有关使用RelayCommand的示例,请阅读Josh的这篇文章

Brian Noyes也有一篇很棒的文章