Passing an Event and a delegate event handler into a generic Helper Method

人走茶凉 提交于 2019-12-22 10:07:08

问题


I have these throughout my code. It's a WP7 Silverlight app.

UIThreadExecutor.UIThreadExec.Execute(() => buttonControl.Click += 
                                new RoutedEventHandler(this.ButtonClickHandler));

So, the above code, on the UI thread assigning buttonControl.Click event to the event handler ButtonClickHandler .. eg:

public void ButtonClickHandler(object sender, System.Windows.RoutedEventArgs e)
{

}

What I'd like is refactor the:

UIThreadExecutor.UIThreadExec.Execute(() => buttonControl.Click += 
                                new RoutedEventHandler(this.ButtonClickHandler));

into a single static but generic helper method - capable for specifying any UI control event and an event handler. Then the method will hook the two together using the UIThreadExecutor class.

Of course, buttonControl could also be any UI control - with different events of the same type. Eg - it could be a RadioButton with a Checked event.

If I goto the definition in VS 2010 of a RadioButton.Checked or Button.Click they are both of the same type:

public event RoutedEventHandler Checked;

I've been scratching my head about this. I thought about, inside my static helper - declaring a delegate (declared at the namespace level):

public delegate void UIControlHandler(object sender, RoutedEventArgs e);

Then my helper method looks like this:

public static void SubscribeToUIEvent(EventHandler eventToSubscribeTo, 
                                                        UIControlHandler handler)
{
    UIThreadExecutor.UIThreadExec.Execute(() => eventToSubscribeTo += handler);
}

That comes up with compilation errors:

Operator '+=' cannot be applied to operands of type 'System.EventHandler' and UIControlHandler
Cannot implicitly convert type UIControlHandler' to 'System.EventHandler'

Can anyone help point me in the right direction? This is driving me crazy.


回答1:


Keyword: MulticastDelegate

Here is a general overview about events/delegates in C#. http://www.codeproject.com/KB/cs/delegates_overview.aspx

Of course you can use interfaces with event declerations too.

Edit 2:

I found this: How to pass an event to a method? This should help, i don't think you'll get a better solution, because it's not possible to pass ref params to a anonymus method.



来源:https://stackoverflow.com/questions/8022406/passing-an-event-and-a-delegate-event-handler-into-a-generic-helper-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!