PROCEDURAL WPF

The previous sections explained how to use XAML to build WPF windows. By using XAML, you can define controls, resources, styles, templates, transformations, and even animations.

Behind the scenes, an application reads the XAML code, and then builds corresponding controls and other objects to make the user interface. Often, it’s easiest to build forms by using the XAML editor, but if necessary, your Visual Basic code can build exactly the same objects.

NOTE
Usually you should build the interface with XAML to increase the separation between the user interface and the code. However, it may sometimes be easier to build dynamic elements in code (for example, in response to data loaded at run time, inputs from the user, or errors).

For example, the MakeButton example program, which is available for download on the book’s website, uses the following Visual Basic code to add a button to its WPF window when you click the initial button:

' Add a new Button to the StackPanel.
Private Sub btnMakeButton_Click() Handles btnMakeButton.Click
    Dim btn As New Button()
    btn.Content = "Make Button"
    AddHandler btn.Click, AddressOf btnMakeButton_Click
    stkButtons.Children.Add(btn)
End Sub

The code starts by creating a new Button object and setting its Content property to the string Make Button. It uses an AddHandler statement to make the btnMakeButton_Click event handler catch the new button’s Click event. Finally the code adds the new button to the stkButtons StackPanel control’s ...

Get Visual Basic 2012 Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.