WPF Controls Overview In VB.NET

Windows Presentation Foundation (WPF) ships with many of the common UI components that are used in almost every Windows application, such as Button, Label, TextBox, Menu, and ListBox.
  • 1388
Windows Presentation Foundation (WPF) ships with many of the common UI components that are used in almost every Windows application, such as Button, Label, TextBox, Menu, and ListBox. Historically, these objects have been referred to as controls. While the WPF SDK continues to use the term "control" to loosely mean any class that represents a visible object in an application, it is important to note that a class does not need to inherit from the Control class to have a visible presence. Classes that inherit from the Control class contain a ControlTemplate, which allows the consumer of a control to radically change the control's appearance without having to create a new subclass. This topic discusses how controls (both those that do inherit from the Control class and those that do not) are commonly used in WPF.

You can add a control to an application by using either Extensible Application Markup Language (XAML) or code. The following example shows how to create a simple application that asks a user for their first and last name. This example creates six controls: two labels, two text boxes, and two buttons, in XAML. All controls can be created similarly.

            <RowDefinition Height="30"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="30"/>
            Enter your first name:
        <TextBox Grid.Row="0" Grid.Column="1"
           Name="firstName" Margin="0,5,10,5"/>

        <Label Grid.Row="1" >
            Enter your last name:
        <TextBox Grid.Row="1" Grid.Column="1"
           Name="lastName" Margin="0,5,10,5"/>

        <Button Grid.Row="2" Grid.Column="0"
          Name="submit" Margin="2">
            View message

        <Button Grid.Row="2" Grid.Column="1"
          Name="Clear" Margin="2">
            Clear Name

The following example creates the same application in code. For brevity, the creation of the Grid, grid1, has been excluded from the sample. grid1 has the same column and row definitions as shown in the preceding XAML example.
Private firstNameLabel As Label
Private lastNameLabel As Label
Private firstName As TextBox
Private lastName As TextBox
Private submit As Button
Private clear As Button

Sub CreateControls()
    firstNameLabel = New Label()
    firstNameLabel.Content = "Enter your first name:"

    firstName = New TextBox()
    firstName.Margin = New Thickness(0, 5, 10, 5)
    Grid.SetColumn(firstName, 1)

    lastNameLabel = New Label()
    lastNameLabel.Content = "Enter your last name:"
    Grid.SetRow(lastNameLabel, 1)

    lastName = New TextBox()
    lastName.Margin = New Thickness(0, 5, 10, 5)
    Grid.SetColumn(lastName, 1)
    Grid.SetRow(lastName, 1)

    submit = New Button()
    submit.Content = "View message"
    Grid.SetRow(submit, 2)

    clear = New Button()
    clear.Content = "Clear Name"
    Grid.SetRow(clear, 2)
    Grid.SetColumn(clear, 1)

End Sub 'CreateControls

Result :


Figure 1

Changing the Appearance of a Control

It is common to change the appearance of a control to fit the look and feel of your application. You can change the appearance of a control by doing one of the following, depending on what you want to accomplish:
  • Change the value of a property of the control.
  • Create a Style for the control.
  • Create a new ControlTemplate for the control.

Changing a Control's Property Value

Many controls have properties that allow you to change how the control appears, such as the Background of a Button. You can set the value properties in both XAML and code. The following example sets the Background, FontSize, and FontWeight properties on a Button in XAML.


    <Button FontSize="14" FontWeight="Bold">
        <!--Set the Background property of the Button to
    a LinearGradientBrush.-->
            <LinearGradientBrush StartPoint="0,0.5"
                <GradientStop Color="Green" Offset="0.0" />
                <GradientStop Color="White" Offset="0.9" />

        View message
The following example sets the same properties in code.

Dim buttonBrush As New LinearGradientBrush()
buttonBrush.StartPoint = New Point(0, 0.5)
buttonBrush.EndPoint = New Point(1, 0.5)
buttonBrush.GradientStops.Add(New GradientStop(Colors.Green, 0))
buttonBrush.GradientStops.Add(New GradientStop(Colors.White, 0.9))

submit.Background = buttonBrush
submit.FontSize = 14
submit.FontWeight = FontWeights.Bold

Result :


Figure 2

Creating a Style for a Control

WPF gives you the ability to specify the appearance of controls wholesale, instead of setting properties on each instance in the application, by creating a Style. The following example creates a Style that is applied to each Button in the application. Style definitions are typically defined in XAML in a ResourceDictionary, such as the Resources property of the FrameworkElement.


    <Style TargetType="Button">
        <Setter Property="FontSize" Value="14"/>
        <Setter Property="FontWeight" Value="Bold"/>
        <Setter Property="Background">
                <LinearGradientBrush StartPoint="0,0.5"
                    <GradientStop Color="Green" Offset="0.0" />
                    <GradientStop Color="White" Offset="0.9" />


You can also apply a style to only certain controls of a specific type by assigning a key to the style and specifying that key in the Style property of your control. For more information about styles, see Styling and Templating.

Creating a ControlTemplate

A Style allows you to set properties on multiple controls at a time, but sometimes you might want to customize the appearance of a Control beyond what you can do by creating a Style. Classes that inherit from the Control class have a ControlTemplate, which defines the structure and appearance of a Control. The Template property of a Control is public, so you can give a Control a ControlTemplate that is different than its default. You can often specify a new ControlTemplate for a Control instead of inheriting from a control to customize the appearance of a Control.
Consider the very common control, Button. The primary behavior of a Button is to enable an application to take some action when the user clicks it. By default, the Button in WPF appears as a raised rectangle. While developing an application, you might want to take advantage of the behavior of a Button--that is, by handling the button's click event--but you might change the button's appearance beyond what you can do by changing the button's properties. In this case, you can create a new ControlTemplate.
The following example creates a ControlTemplate for a Button. The ControlTemplate creates a Button with rounded corners and a gradient background. The ControlTemplate contains a Border whose Background is a LinearGradientBrush with two GradientStop objects. The first GradientStop uses data binding to bind the Color property of the GradientStop to the color of the button's background. When you set the Background property of the Button, the color of that value will be used as the first GradientStop. For more information about data binding, see Data Binding Overview. The example also creates a Trigger that changes the appearance of the Button when IsPressed is true.

    <!--Define a template that creates a gradient-colored button.-->
    <Style TargetType="Button">
        <Setter Property="Template">
                <ControlTemplate TargetType="Button">
                            <LinearGradientBrush StartPoint="0,0.5"
                                <GradientStop Color="{Binding Background.Color,
                    RelativeSource={RelativeSource TemplatedParent}}"
                            Offset="0.0" />
                                <GradientStop Color="White" Offset="0.9" />
                        <!--Change the appearance of
          the button when the user clicks it.-->
                        <Trigger Property="IsPressed" Value="true">
                            <Setter TargetName="Border" Property="Background">
                                    <LinearGradientBrush StartPoint="0,0.5"
                                        <GradientStop Color="{Binding Background.Color,
                    RelativeSource={RelativeSource TemplatedParent}}"
                                Offset="0.0" />
                                        <GradientStop Color="DarkSlateGray" Offset="0.9" />


    <Button Grid.Row="2" Grid.ColumnSpan="2" Name="submitName"
        Background="Green">View message</Button>
Note: The Background property of the Button must be set to a SolidColorBrush for the example to work properly.
Subscribing to Events
You can subscribe to a control's event by using either XAML or code, but you can only handle an event in code. The following example shows how to subscribe to the Click event of a Button.


<Button Grid.Row="2" Grid.ColumnSpan="2" Name="submitName" Click="submit_Click"
  Background="Green">View message</Button>
AddHandler submit.Click, AddressOf submit_Click

The following example handles the Click event of a Button.
Private Sub submit_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    MessageBox.Show("Hello, " + firstName.Text + " " + lastName.Text)

End Sub 'submit_Click

Most classes that inherit from the Control class have the capacity to contain rich content. For example, a Label can contain any object, such as a string, an Image, or a Panel. The following classes provide support for rich content and act as base classes for most of the controls in WPF.

For more information about these classes, see Controls Content Model Overview.


More Articles

© 2013 dotNetheaven. All rights reserved.