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

FoxInCloud Stats

FoxInCloud sent this link a while back about their statistics regarding visits to their site: http://foxincloud.com/blog/2017/12/27/VFP-community-lessons-from-foxincloud-site.html What's interesting here is the breakdown of people. Yes, I think it's understandable that the Fox community is getting older. Another factor is the growth of the mobile and web environments taking over development. These environments really do push people towards the newer non-SQL or free SQL/hosted environments but more towards hosted storage options like Amazon and Google. A tool like FoxInCloud that helps MOVE existing applications to the cloud inherently competes with those environments. But FoxInCloud also allows developers to extend their application further by giving them a starting point using Javascript and the basic CSS (such as Bootstrap). If you're not rebuilding your application from scratch, it's certainly a great step forward. FoxPro VFP

5 Great Reasons to attend Virtual FoxFest

What's coming up? Virtual FoxFest is coming up soon (sessions start October 14th). Like last year, the conference is entirely virtual yet includes great breakdown rooms and sessions to add that nice one-on-one feel that you get in person. It's also staggered so you can choose which days you want to attend - October 14th, 20th and 26th. This is great if you can't break away for a consecutive three days. But really, I've gone through the sessions and I see five great sessions that I'm eager to check out. 1. A Decade of Thor (Rick Schummer) Thor has been an extension for Visual FoxPro that many developers swear by, yet many don't know even exists. Visual FoxPro's built-in extensions are great but Jim Nelson's Thor supercharges your IDE. I can't believe it's been ten years - so Rick's session should be able to not just whet your appetite but give you all the reasons you should be using it. 2. VFP C++ compiler.  Last year, we saw DotNetX as well