WPF: Code behind

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

We have mentioned that once we create a WPF application, there are 2 main files that are created by Visual Studio.

  1. MainWindow.xaml
  2. MainWindow.xaml.cs

The second file, MainWindow.xaml.cs is called the code behind file.

Text box is also a very common WPF control.  Now we will add a text box so that once we click on a button, a text will be displayed in the text box.

sayhello

MainWindow.xaml
<Window x:Class="SayHello.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>
        <Button HorizontalAlignment="Stretch" Margin="180,180,160,100" Click="Button_Click">Say Hello</Button>
        <TextBox  Name="textBox1" HorizontalAlignment="Stretch" Margin="100,50,120,200" Text="This is a text box." />

    </Grid>
</Window>
MainWindow.xaml.cs
using System.Windows;

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

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            textBox1.Text = "Hello There!";
        }
    }
}

Now we look at what we have added to the xaml file and and code behind file to have made the application works.

<Button HorizontalAlignment="Stretch" Margin="180,180,160,100" Click="Button_Click">Say Hello</Button>
<TextBox  Name="textBox1" HorizontalAlignment="Stretch" Margin="100,50,120,200" Text="This is a text box." />

In the Buttun control, we have added a Click event and the method Button_Click.

In the TextBox control, we have also added an instance called textBox1.

So once the button is clicked, the Text in the TextBox control will be updated by the Button_Click method in the code behind file.

textBox1.Text = "Hello There!";

hellothere

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