How do I fix 'compiler error - cannot convert

2019-02-16 13:31发布

 public MainWindow()
 {
    CommandManager.AddExecutedHandler(this, ExecuteHandler);
 }

 void ExecuteHandler(object sender, ExecutedRoutedEventArgs e)
 {
 }

Error 1 Argument 2: cannot convert from 'method group' to 'System.Delegate'

标签: c# delegates
2条回答
孤傲高冷的网名
2楼-- · 2019-02-16 13:54

You cannot pass a "method" directly as a parameter, you need to pass an expression. You can either wrap the method into a delegate:

CommandManager.AddExecutedHandler(this, new ExecutedRoutedEventHandler(ExecuteHandler));
CommandManager.AddExecutedHandler(this, (Action<object,ExecutedRoutedEventArgs>) ExecuteHandler);

or into a lambda – which is my personal favorite, since you don't need to memorize a delegate name:

CommandManager.AddExecutedHandler(this, (s, e) => ExecuteHandler(s, e));
查看更多
戒情不戒烟
3楼-- · 2019-02-16 13:56

I guess there are multiple ExecuteHandler with different signatures. Just cast your handler to the version you want to have:

CommandManager.AddExecuteHandler(this, (Action<object,ExecutedRoutedEventArgs>)ExecuteHandler);
查看更多
登录 后发表回答