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

Blogs and RSS come to Microsoft.com

MS has just introduced their portal and it's pretty comprehensive. Nothing quite like learning that some people use AIM instead of MSN messenger, or that there really may be a need for supporting 4 monitors ( Cyrus Complains ) However, it's really a great sign that MS is serious about supporting the blogging community which seems to have um, exploded in size in the past year. Blogs and RSS come to Microsoft.com

Elevating Project Specifications with Three Insightful ChatGPT Prompts

For developers and testers, ChatGPT, the freely accessible tool from OpenAI, is game-changing. If you want to learn a new programming language, ask for samples or have it convert your existing code. This can be done in Visual Studio Code (using GitHub CoPilot) or directly in the ChatGPT app or web site.  If you’re a tester, ChatGPT can write a test spec or actual test code (if you use Jest or Cypress) based on existing code, copied and pasted into the input area. But ChatGPT can be of huge value for analysts (whether system or business) who need to validate their needs. There’s often a disconnect between developers and analysts. Analysts complain that developers don’t build what they asked for or ask too many questions. Developers complain that analysts haven’t thought of obvious things. In these situations, ChatGPT can be a great intermediary. At its worst, it forces you to think about and then discount obvious issues. At best, it clarifies the needs into documented requirements. ...

Programmers vs. Developers vs. Architects

I received an email this morning from Brandon Savage 's newsletter. Brandon's a PHP guru (works at Mozilla) but his newsletter and books have some great overall perspectives for developers of all languages. However, this last one (What's the difference between developers and architects?) kind of rubs me the wrong way. Either that, or I've just missed the natural inflation of job descriptions. (maybe, it's like the change in terminology between Garbage man and Waste Engineer or Secretary and Office Administrator) So maybe it's just me - but I think there's still a big difference between Programmer, Developer and then of course, architect. The key thing here is that every role has a different perspective and every one of those perspectives has value. The original MSF create roles like Product Manager, Program Manager, Developer, Tester, etc - so every concept may pigeon hole people into different roles. But the statements Brandon makes are often distinction...