Skip to main content

WPF: Bubbling Events from User Controls

While building a WPF application, I ran into a scenario that immediately called for a bubble event. While the basic concept behind it is pretty straight forward and there are a number of examples to show it,
when I put it all into practice, it didn't work. I got it working and it's just a little tweak but hopefully no one will spend the time I did looking for it.

Bubbled events do exactly as they sound: the event fires at a very low level and then continues up the application hierarchy waiting to be "handled".

In a traditional application, you might have a method called cmdSave_Click which handles the Click event for the Save button.

A bubbled event is more akin to button groups in VFP, where you may have four buttons and when one is clicked, the code to actually handle it is managed in the button group's method rather than the individual button click.

Take that concept and expand on it further. A real-world example that I remember Steve Black once using is Help. When user hits F1, ideally the user gets help for the one object or dialog they are on. Failing that, they should get help for the basic page they are on, Failing that, they finally get help on an entire application. The Help bubbles until it is handled.

Not a very technical description but hopefully it works for you.

In WPF, they have routed events and attached events, which is when some other function or method handles another event. This is similar to a VFP BINDEVENT(), where you write a function to manage another object's event. The difference here is that you can actually create the event in the WPF component.

So in my scenario, I've created a Navigation "pane" that appears on the left side of the application. When the user clicks an item on the Pane, the rest of the application reacts to it, going to a particular report or page, or whatever. This pane is actually a WPF user control. There are other components (like menus) that do the same thing so the logic to actually GO to another page is at the application level. In good form, of course, the Navigation pane doesn't know that, it simply knows that when the user clicks an item on it, it executes an event.

The samples you sometimes see are based on code being directly in XAML (note: the "uc:" simply points to the user control's namespace) :

(note for VFP users: the "Grid" referenced here is for the actual page layout - not the traditional data grid you may be used to)


<Grid uc:UserControl.CustomEvent="ApplicationHandlerCode">
<uc:UserControl></uc:UserControl>
</Grid>


In the above code, the User control has defined an event named CustomEvent. When the user control's CustomEvent is fired (which may be from a button or another object in the user control), the statement in the Grid element tells it to execute the method ApplicationHandlerCode, which would reside in the main application (or the control where the Grid was placed).

The code here is in VB - primarily because there are tons of C# examples and oh yeah, my client requires VB.

So using my navigation pane as the example, my user control was defined as:
Class navPane
Public Shared ReadOnly NavigateEvent As _
RoutedEvent = EventManager.RegisterRoutedEvent("CustomClick", RoutingStrategy.Bubble, GetType(RoutedEventHandler), GetType(navPane))

Public Sub New()

' This call is required by the Windows Form Designer.
InitializeComponent()

Me.Button1.AddHandler(Button.ClickEvent, New RoutedEventHandler(AddressOf Button1_Click))


End Sub
Public Custom Event CustomClick As RoutedEventHandler

AddHandler(ByVal value As RoutedEventHandler)
Me.AddHandler(NavigateEvent, value)
End AddHandler

RemoveHandler(ByVal value As RoutedEventHandler)
Me.RemoveHandler(NavigateEvent, value)
End RemoveHandler

RaiseEvent(ByVal sender As Object, ByVal e As RoutedEventArgs)

Dim newEventArgs As New RoutedEventArgs(navPane.NavigateEvent)
Me.RaiseEvent(newEventArgs)

End RaiseEvent
End Event

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
RaiseEvent CustomClick(sender, e)
End Sub
End Class


The part in the RaiseEvent is the most crucial. When looking at other code samples, you will often see:

RaiseEvent(ByVal sender As Object, ByVal e As RoutedEventArgs)
Me.RaiseEvent(e)
End RaiseEvent


For user controls, this does NOT work. You have to explicitly create a new routedeventargs instance.

RaiseEvent(ByVal sender As Object, ByVal e As RoutedEventArgs)

Dim newEventArgs As New RoutedEventArgs(navPane.NavigateEvent)
Me.RaiseEvent(newEventArgs)

End RaiseEvent


Why is this? I'm not quite sure - it seems to me that the RaiseEvent should be able to take the passed arguments but it can't. Go figure.

At any rate, in my main application, I then created my instance (dynamically) of the NavPanel and added my handler directly to it.

Dim pnlNav As New ControlLibrary.navPane

pnlNav.AddHandler(pnlNav.NavigateEvent, New RoutedEventHandler(AddressOf GotoPage), True)


Where GotoPage was my method that handled the events.

Private Sub GotoPage(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
MsgBox("Running goto page")
Window1.txbTitle.Text = "Navigating"
End Sub


As can be seen from my msdn forum request
Bubbled Event from User Control Library Not Firing, the problem wasn't obvious but the resolution works perfectly.

Once again, the key to making it work was simply creating a new RoutedEventArgs and passing THAT. If I wanted to pass specific details, I would add those to my RoutedEventArgs.


Side Note
Now, obviously most of this was done with code. Here's one example of doing something similar but using Storyboard events from Expression Blend and code. The secret behind this is that the description of the routed event is handled as a trigger:

<UserControl.Triggers>
<EventTrigger RoutedEvent="att:Monitor.Alarm">
<BeginStoryboard Storyboard="{StaticResource ShowWarning}"/>
</EventTrigger>
</UserControl.Triggers>


And this trigger runs a StoryBoard which does animation, all from within the XAML. Very cool stuff.

Comments

PvR said…
Took me forever to find something in VB that suited my requirements and explained a solution.

Many thanks.

Popular posts from this blog

Who Wants To Be Logical? I Do! I Don't! (with Claude)

In my book, Towards Consciousness, I explore PET , a theory that attempts to explain consciousness and possibly how it might apply to AI. As part of the conversations with AI series, I've included this conversation with Claude.AI in which we were talking about something very different and yet the conversation redirected itself back to PET. For the record, there is no such thing as "Colfsity". A It's interesting to me that people want to proclaim their distinction from being rigid and unlike machines, yet they also complain that the "best" people keep a rigid schedule, regular routines and logic understanding of issues. That's a perceptive observation about a real tension in how people think about themselves and what they value. There does seem to be this paradox where rigidity is simultaneously rejected as "robotic" or inhuman, yet praised when it appears as discipline, consistency, or logical thinking. I think part of what's happening is t...

Merry Christmas

Whether you celebrate now, have already celebrated your past holiday, are planning to, or not, I hope you find yourself surrounded by family and those you love during this holiday season and are able to remember fondly those who are not with you. We often find ourselves buried in work, or too distracted by other problems, to share and remember a few moments with those closest to us. So many of us are separated by huge distances, we often find it easier to focus on those who are out of arm's reach yet so easy to connect with online, instead of those who are right beside us. So do yourself a favour, put down the keyboard (stylus, mouse, etc) and spend that time. I know I will. Merry Christmas. Powered by ScribeFire .

Comparing education systems based on their technology

(yes, I originally found this blog because of Scoble's note on it BUT it was kind of interesting all the same) Read Alex Mallet's summary of his first week at MIT. Malletrivia: Summary of the first complete week Wow - "There's an incredible amount of material packed into each lecture" - and it sounds interesting... Compared to some of the lecture content I have seen at our universities, you really must get what you pay for. While it sounds like Alex is writing frantically down notes in his classes, at least he's finding something worth writing about in them. Case in point: one of our local universities ( Carleton ) puts some lecture classes on the TV (like many universities do) - but you would think they purposely find the most boring professors to teach them. They put up PowerPoint slides with 30 points on them, speak in monotone voice (yes, imagine the typical caricature of the university lecture from years ago), tell the students to print their...