locked
Why are Buttons different in VB and C# solutions?

    Question

  • As a C# developer, I was surprised to discover in some VB code that the XAML Click attribute is optional for Buttons with x:Names.

    In fact, if you create a Button in VS2013 (Windows Store VB solution), name it, then double-click it, an event handler stub will be created in the code-behind but no Click attribute will be added to the XAML.   And it works!  Click the button and the click event will be executed.

    <Button x:Name="myButton">Hello</Button>
     Private Sub myButton_Click(sender As Object, e As RoutedEventArgs) Handles myButton.Click
        End Sub

     I could not find this behavior documented.

    Try the same in a C# solution, and the Click attribute will always be added whether the button has been named or not.  The Click attribute is required to hook the button up to the event handler.

    Is it the common practice of VB programmers to not use the XAML Click attribute for Buttons with names?  Is it a new feature or an arcane one?  A VB XAML file created this way would not be portable to a C# solution.

    Saturday, May 10, 2014 3:01 PM

Answers

All replies

  • Hi, it is normal, VB use WithEvents and Handles to add event handler, please see below link:

    http://msdn.microsoft.com/en-us/library/stf7ebaz(v=vs.90).aspx

    http://msdn.microsoft.com/en-us/library/6k46st1y.aspx

    http://msdn.microsoft.com/en-us/library/aty3352y.aspx

    And you also can use the same way as C# to add event handler, for example:

    <Button x:Name="myButton" Click="myButton_Click">Hello</Button>
    Private Sub myButton_Click(sender As Object, e As RoutedEventArgs)
    End Sub
    in this way, you don't need to use "Handles myButton.Click" in Private Sub myButton_Click

    • Edited by lapheal Saturday, May 10, 2014 3:15 PM
    • Marked as answer by jrboddie Saturday, May 10, 2014 3:43 PM
    Saturday, May 10, 2014 3:13 PM
  • While C# doesn't have a direct analogue to "Handles", you can add a Click handler from code in C# without including it in the Xaml:

    myButton.Click += myButton_Click;

    As lapheal says though, the conventions VB programmers and C# programmers typically use are historically different, and the designer's default behaviour caters to the typical conventions for each community.

    Saturday, May 10, 2014 3:26 PM
    Owner
  • Thanks.  I didn't notice the "Handles" business in the event handler.  I am quite familiar with the methods to hook up event handlers in XAML and the code-behind for C#,

    So, there are two options to make a portable XAML file:

    1. Use the Click attribute for the buttons and event handlers in VB without the Handles name.
    2. Don't use the Click attribute and wire up the C# handlers in the page constructor.

    • Edited by jrboddie Saturday, May 10, 2014 3:53 PM
    Saturday, May 10, 2014 3:52 PM