简体   繁体   English

WPF中的内联事件处理程序

[英]Inline Event Handler in WPF

I create textbox controls dynamically through code behind. 我通过后面的代码动态创建文本框控件。 I have to bind a handker on 'LostFocus' event of the newly created textbox. 我必须在新创建的文本框的“ LostFocus”事件上绑定一个handker。 And then add it to a Listbox. 然后将其添加到列表框。 I am able to do this with below code. 我可以使用下面的代码来做到这一点。

TextBox txtBox = new TextBox();
txtBox.Text ="XXXX";
txtBox.Width = 100;
txtBox .LostFocus += new RoutedEventHandler(updateTextHandler);
listBox.Items.Add(txtBox);

But, I want to shorten this code and do like 但是,我想缩短这段代码并喜欢

listServer.Items.Add(new TextBox()
                {
                    Text = "XXXXX",
                    Width = 100

                });

How do I add event handler for the controls initialized inline? 如何为内联初始化的控件添加事件处理程序? I tried, but doesn't work 我试过了,但是没用

this.LostFocus +=new RoutedEventHandler(updateButtonHandler) 

As you can read in MSDN : 正如您可以在MSDN中阅读的:

Object initializers let you assign values to any accessible fields or properties of an object at creation time 对象初始化程序使您可以在创建时将值分配给对象的任何可访问字段或属性

Events aren't fields or properties so you can't set them in initializer. 事件不是字段或属性,因此无法在初始化程序中进行设置。 Especially as they are not accessible by = but only by += . 尤其是因为=不能访问它们,而+=只能访问它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM