Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Wpf 对RoutedEventHandler使用Lambda表达式_Wpf - Fatal编程技术网

Wpf 对RoutedEventHandler使用Lambda表达式

Wpf 对RoutedEventHandler使用Lambda表达式,wpf,Wpf,我正在使用以下代码成功安装事件处理程序: this.AddHandler(MouseLeftButtonDownEvent, new RoutedEventHandler(tabLabel_MouseLeftButtonDown), true); ... void tabLabel_MouseLeftButtonDown(object sender, EventArgs e) { this.IsSelected = true; } 现在,我尝试使用Lambda表达式使代码更加紧凑,如

我正在使用以下代码成功安装事件处理程序:

this.AddHandler(MouseLeftButtonDownEvent, new RoutedEventHandler(tabLabel_MouseLeftButtonDown), true); ...
void tabLabel_MouseLeftButtonDown(object sender, EventArgs e)
{
    this.IsSelected = true;
 }
现在,我尝试使用Lambda表达式使代码更加紧凑,如下所示:

this.AddHandler(MouseLeftButtonDownEvent, (s, e) => { this.IsSelected = true; }, true);
它向我提供了错误消息:

无法将lambda表达式转换为类型“System.Delegate”,因为它不是委托类型

我不知道该怎么做。有可能吗

   this.AddHandler(MouseLeftButtonDownEvent, new RoutedEventHandler((sender,e) => this.IsSelected=true), true); 
问题的出现是因为编译器知道AddHandler的第二个参数的类型是System.Delegate,它是抽象的。如果没有具体类型,则无法推断lambda中参数的类型

我们不必在这里使用RoutedEventHandler,我们可以创建具有相同签名的内容:
Action
,它也可以工作,但上面的版本较短

    this.AddHandler(MouseLeftButtonDownEvent,  new Action<object,EventArgs>((sender, e) => IsSelected = true), true);
this.AddHandler(MouseLeftButtonDownEvent,新操作((发送者,e)=>IsSelected=true),true);
问题的出现是因为编译器知道AddHandler的第二个参数的类型是System.Delegate,它是抽象的。如果没有具体类型,则无法推断lambda中参数的类型

我们不必在这里使用RoutedEventHandler,我们可以创建具有相同签名的内容:
Action
,它也可以工作,但上面的版本较短

    this.AddHandler(MouseLeftButtonDownEvent,  new Action<object,EventArgs>((sender, e) => IsSelected = true), true);
this.AddHandler(MouseLeftButtonDownEvent,新操作((发送者,e)=>IsSelected=true),true);

OP试图使用lambda表达式使代码更紧凑。@虽然这确实回答了问题,但如果您向OP解释为什么您的代码有效而他的代码无效,可能会有所帮助。非常感谢。解释很有帮助,我现在知道我需要更仔细地研究什么(委托的东西)。OP试图使用lambda表达式使代码更紧凑。@虽然这确实回答了问题,但如果您向OP解释为什么您的代码有效而他的代码无效,可能会有所帮助。非常感谢。这个解释很有帮助,我现在知道我需要更仔细地研究什么了(代表的东西)。