WPF: Design the UI using designer

This entry is part 7 of 54 in the series Learn WPF

Visual Studio provides some tools that make designing the controls rather easy.

label

Now using the designer, we put a button and a label to the application.

From the toolbox on the left hand side of the Visual Studio, we drag a Label control followed by a Button control to the application.

The designer will automatically insert for us the following code into the XAML.

<Label Content="Label" HorizontalAlignment="Left" Height="91" Margin="118,67,0,0" VerticalAlignment="Top" Width="263"/>
<Button Content="Button" HorizontalAlignment="Left" Margin="221,216,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>

Now we need to add an instance name to the Label so that we can output a new text to the Label.

Click on the Label box and on the bottom right hand side on the screen, we can see the Properties of the Label box control.

We give a name label1 to the Label box.

properties

Notice that after we have added a name, the designer will update for us a label1 instance in the xaml.

<Label x:Name="label1" Content="Label" HorizontalAlignment="Left" Height="91" Margin="118,67,0,0" VerticalAlignment="Top" Width="263"/>

Now double click on the button in the designer and the visual studio will bring us to MainWindow.xaml.cs where the Button_Click method will be created for us automatically.

private void Button_Click(object sender, RoutedEventArgs e)
        {     
        }

In the method, we just have to add the following line:

label1.Content = "Hi There.";

.The final xaml and code behind will be as follow:

<Window x:Class="HelloLabel.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Label x:Name="label1" Content="Label" HorizontalAlignment="Left" Height="91" Margin="118,67,0,0" VerticalAlignment="Top" Width="263"/>
        <Button Content="Button" HorizontalAlignment="Left" Margin="221,216,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>

    </Grid>
</Window>

.

Final code behind:
using System.Windows;

namespace HelloLabel
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            label1.Content = "Hi There.";
        }
    }
}

Now click on start to run the application and click on the button to see the label text updated.

Series Navigation<< WPF: OnLoad event
WPF: StackPanel >>