Tuesday, 26 June 2012

Binding To Event At Runtime In Windows 8 Metro

So I wanted to use the MVVM pattern in Win8 Metro WPF, but was without the classes and functionality I would use in WPF4. So I decided to create my own, but I got the error:

Adding or removing event handlers dynamically is not supported on WinRT events.

I found a blog post on the MSDN where some guy posted about using the WindowsRuntimeMarshal to get around that, but he didn't post a code sample. So, I decided to figure it out, and let everyone know!

So here's the code:

var eventName = "Click";
var myButton = new Button();
var runtimeEvent = myButton.GetType().GetRuntimeEvent(eventName);
var handlerType = runtimeEvent.EventHandlerType;
Func<RoutedEventHandler, EventRegistrationToken> add = (a) => { return (EventRegistrationToken)runtimeEvent.AddMethod.Invoke(myButton, new object[] { a }); };
Action<EventRegistrationToken> remove = (a) => { runtimeEvent.RemoveMethod.Invoke(runtimeEvent, new object[] { a }); };
RoutedEventHandler handler = (a, b) => Command.Execute(b);
WindowsRuntimeMarshal.AddEventHandler<RoutedEventHandler>(add, remove, handler);

So that's how we can add an event handler to an event at runtime in WinRT. Pretty simple, really. The one limitation of this code is that if you are trying to bind to an event that isn't a RoutedEvent, you're going to have to re-do the code. But I'm sure this is able to become a generic function with a little bit more work.


  1. Here is a database compatible with Windows Runtime:

  2. The expansion of internet and intelligence in business process lead the way to huge volume of data. It is important to maintain and process these data to be efficient in data handling. Hadoop Training in Chennai | Big Data Training in Chennai

  3. this informative content is really nice and good , give some more information about this blog.

    dotnet training in chennai

  4. Nice..Its informative...Its very useful for me to understand..Keep on sharing..
    Java Training in Chennai

  5. ERPTREE is a leading oracle fuison HCM Training Institute. we offer this course through online we have great
    experience in succeeding students through online courses. we can calculate our performance through their honest
    comments in our sites in supporting our services. we have referral program so candidates can earn money through
    referral. you can share your live experience with other can generate you some money.

    Oracle fusion HCM Online Training

    Oracle Fusion HCM Training

  6. Wonderful article.I understand the concepts of cloud computing. it' s really superb.
    VLSI Project Center in Chennai | VLSI Project Center in Velachery

  7. Thanks for one marvelous posting! I enjoyed reading it; you are a great author. I will make sure to bookmark your blog and may come back someday. I want to encourage that you continue your great posts, have a nice weekend!

    Data Science Training in Chennai