Alessandro Del Sole's Blog

/* A programming space about Microsoft® .NET® */
posts - 159, comments - 0, trackbacks - 0

My Links

News

Your host

This is me! This space is about Microsoft® .NET® and Microsoft® Visual Basic development. Enjoy! :-)

These postings are provided 'AS IS' for entertainment purposes only with absolutely no warranty expressed or implied and confer no rights.

Microsoft MVP

My MVP Profile

I'm a VB!

Watch my interview in Seattle

My new book on VB 2015!

Pre-order VB 2015 Unleashed Pre-order my new book "Visual Basic 2015 Unleashed". Click for more info!

My new book on LightSwitch!

Visual Studio LightSwitch Unleashed My book "Visual Studio LightSwitch Unleashed" is available. Click the cover!

Your visits

Follow me on Twitter!

CodePlex download Download my open-source projects from CodePlex!

Article Categories

Archives

Post Categories

.NET Framework

Blogroll

Help Authoring

Microsoft & MSDN

Setup & Deployment

Visual Basic 2005/2008/2010

WPF and the Handles keyword

When developing WPF applications with Visual Basic 2008 you may encounter a particular problem due to the bad usage of the Handles clause in events handling. In other words, if you assign an event handler to an user control in XAML code and then you specify an Handles clause for the same user control when writing the event handler, the event is handled twice and the consequences can be dangerous.

For example, let's consider the following XAML code which just declares a button:

        <Button Width="100" Height="30" Name="Button1" Click="Button1_Click" />

As you can see, I assigned an event handler to the control. Now let's implement the event handler in Visual Basic code as follows:

    'This is not correct when setting an event handler via XAML

    Private Sub Button1_Click(ByVal sender As System.Object, _

                              ByVal e As System.Windows.RoutedEventArgs) _

                              Handles Button1.Click

 

        MessageBox.Show("You clicked!")

    End Sub

The comment above is quite clear: this technique is not valid, because the event is handled twice. But why does this happen? Let's try to understand how things work.

Build the project and then activate the Show all files command in Solution Explorer, then double click the Window1.g.vb file (or the .g.vb file related to your window), that is located in the Obj\Debug sub-folder (or Obj\Release if you're in Release mode). This file contains a partial class where the IDE stores controls' definitions. You should find the following code, that Visual Studio has added just after you wrote the above seen XAML code:

    <System.Diagnostics.DebuggerNonUserCodeAttribute(),  _

     System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never),  _

     System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")>  _

    Sub System_Windows_Markup_IComponentConnector_Connect(ByVal connectionId As Integer, ByVal target As Object) Implements System.Windows.Markup.IComponentConnector.Connect

        If (connectionId = 1) Then

            Me.Button1 = CType(target,System.Windows.Controls.Button)

           

            #ExternalSource("..\..\Window1.xaml",6)

            AddHandler Me.Button1.Click, New System.Windows.RoutedEventHandler(AddressOf Me.Button1_Click)

            

            #End ExternalSource

            Return

        End If

        Me._contentLoaded = true

    End Sub

Now don't take care of the method body and attributes, but please pay attention to the AddHandler statement. This line of code means that Visual Studio has done the job for us, specifying what it really needs to correctly handle the event. This also means that if you add the clause Handles, this will produce an effect that is the same of adding another AddHandler statement. Now we can understand because that problem is raised.

At this point we have two ways to solve the problem. The first one: we can declare the event handler in XAML code without using Handles in VB code:

        <Button Width="100" Height="30" Name="Button1" Click="Button1_Click" />

 

    Private Sub Button1_Click(ByVal sender As System.Object, _

                              ByVal e As System.Windows.RoutedEventArgs)

         MessageBox.Show("You clicked!")

    End Sub

Or the second one: we don't assign an event handler in XAML code but we can use Handles in VB code:

        <Button Width="100" Height="30" Name="Button1" />

    Private Sub Button1_Click(ByVal sender As System.Object, _

                              ByVal e As System.Windows.RoutedEventArgs) _

                              Handles Button1.Click

        MessageBox.Show("You clicked!")

    End Sub

I hope this can be useful!

Alessandro

Print | posted on giovedì 15 gennaio 2009 23:53 | Filed Under [ Visual Basic Windows Presentation Foundation ]

Feedback

No comments posted yet.

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 5 and 3 and type the answer here:

Powered by:
Powered By Subtext Powered By ASP.NET