Search code examples
silverlighteventsroutespreviewuielement

Why do my Silverlight UIElements NOT have OnPreview events?


I'm building a custom Silverlight UserControl which needs to listen to events using Preview/Tunneling, but for some reason the compiler is telling me they are not recognized or accessible.

For example, I can add an event handler to MouseLeftButtonDown, but not PreviewMouseLeftButtonDown. This doesn't make sense because according to Microsoft (http://msdn.microsoft.com/en-us/library/system.windows.uielement_members(v=VS.100).aspx) all UIElements should have Preview events attached.

Any ideas as to why this is happening? I'm using Visual Studio 2010 Trial, Blend 4 RC and .Net 4, if that makes a difference.


Solution

  • Silverlight does not support preview events nor does it support routed events (bubbling/tunneling) except for a few core events.

    If you are trying to create a control that works with both WPF and Silverlight, you will need to take a different approach. Depending on what you're trying to do, you may be able to accomplish what you want by rigging up a handler in code and specifying that you want handled events too.

    // the last parameter indicates we want to receive events that
    // were marked as e.Handled = true by other listeners
    // this type of event handler can only be done in code
    myUserControl.AddHandler(
        UIElement.MouseLeftButtonDownEvent,
        OnMouseLeftButtonDown,
        true
    );