当Button完成ICommand的执行时,是否有办法获取回调?

问题描述 投票:0回答:1

是否可以在控件的按钮(最终执行ICommand)中附加处理程序(回调),以便控件知道命令执行的时间?

wpf callback commandbinding
1个回答
1
投票

您可以创建抽象的CallbackableCommand来引发回调方法。

abstract class CallbackableCommand : ICommand
  {
    private IInputElement getRaisedElement()
    {
      return Keyboard.FocusedElement;      
    }

    public void Execute(object parameter)
    {
      ExecuteImpl(parameter);
      var element = getRaisedElement();
      if(element == null) return;

      //var ci = typeof(ExecutedRoutedEventArgs).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)[0];
      //var routedEventArgs = (RoutedEventArgs)ci.Invoke(new object[] { this, parameter });
      var routedEventArgs = new RoutedEventArgs();
      //routedEventArgs.RoutedEvent = CommandManager.ExecutedEvent;
      routedEventArgs.RoutedEvent = Callbackable.CommandExecutedEvent;
      routedEventArgs.Source = element;
      routedEventArgs.Handled = false;

      element.RaiseEvent(routedEventArgs);            
    }    

    public abstract void ExecuteImpl(object parameter);

    abstract public bool CanExecute(object parameter);

    abstract public event EventHandler CanExecuteChanged;
  }

从CallbackableCommand继承命令并覆盖CanExecute,CanExecuteChanged和ExecuteImpl(而不是Execute)

  class SimpleCommand : CallbackableCommand
  {
    public override void ExecuteImpl(object parameter)
    {
      MessageBox.Show("Simple command execute with parameter: " 
        + parameter ?? "null");
    }

    public override bool CanExecute(object parameter)
    {
      return true;
    }

    public override event EventHandler CanExecuteChanged;
  }

指定CommandExecuted事件的自己的元素:

  public class Callbackable : ContentControl
  {
    public static readonly RoutedEvent CommandExecutedEvent = EventManager.RegisterRoutedEvent(
        "CommandExecuted", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(Callbackable));

    // Provide CLR accessors for the event
    public event RoutedEventHandler CommandExecuted
    {
      add { AddHandler(CommandExecutedEvent, value); }
      remove { RemoveHandler(CommandExecutedEvent, value); }
    }
  }

编辑:在您的控件中指定Callbackable.CommandExecuted事件

<Grid>
    <Grid.Resources>
        <local:SimpleCommand x:Key="btnCommand" />            
    </Grid.Resources>
    <local:Callbackable>
        <Button Command="{StaticResource btnCommand}"   
                CommandParameter="param"                
                local:Callbackable.CommandExecuted="Button_Executed" >
            Click me
        </Button>
    </local:Callbackable>
</Grid>

已执行的事件处理程序:

private void Button_Executed(object sender, ExecutedRoutedEventArgs e)
{
  MessageBox.Show("Executed");
}
© www.soinside.com 2019 - 2024. All rights reserved.