events - Why I can't pass RoutedEventHandler directly in c# -


I got a UserControl where I want to make an event public:

  public Event RoutedEventHandler CloseButtonClicked;  

To post this incident, do not the following:

  public MyUserControl () {InitializeComponent (); CloseButton.Click + = CloseButtonClicked; }  

The following does while working:

  Public MyUserControl () {InitializeComponent (); CloseButton.Click + = (Sender, Args) => CloseButtonClicked (Sender, Args); }  

Why is that so?

The difference between your two is when the CloseButtonClicked event is evaluated .

In the first, non-example example, the value of the event field is evaluated when the program statement CloseButton.Click + = CloseButtonClicked; is executed. Unless you already set up a field for some useful values, then when the click event is raised later nothing will happen.

Second, for example, the example work example event field is evaluated when the click event is picked up. This statement declares an anonymous method (via lambda expression), which invites delegate example stored in the CloseButtonClicked event field on execution. So that field is set up till the event is picked up, it does not matter that when you execute closeButton, not sets. Click = (Sender, Args) => CloseButtonClicked (Sender, Args); statement.

Note that with one tap reference exception the second statement will fail, if CloseButtonClicked Event field has not been started when click event When raising the events, you should first protect it by checking the tap (and locally securing the price against securing a thread race conditions) for example:

  closeButton.Click + = (Prev A, Arges) {RoutedEventHandler handler = CloseButtonClicked; If (handler! = Null) {handler (sender, args); }};  

Naturally, the above boilerplate is often explained in a subsidiary method (extension or otherwise).


Comments

Popular posts from this blog

java - Can't add JTree to JPanel of a JInternalFrame -

javascript - data.match(var) not working it seems -

javascript - How can I pause a jQuery .each() loop, while waiting for user input? -