C# WPF First Program


This entry is part 2 of 18 in the series C# WPF

wpf-myfirst

Just to get started, the screen shot of our first program is shown here. It is our version of a Hello World program. As simple as possible. Using Visual Studio 2015, we created a new WPF program using C#. Then a button was dragged on to the Designer window. The dimensions of the main window ware changed. The Title of the main window was changed. The name of the button was changed from button to mybutton. A click event was added to the button by double-clicking the button in the designer. Message box code was added to the MainWindow.xaml.cs file.

This post is part of a series of posts that fall under the topic XAML. In future posts we will talk more about what XAML is.

The code for this project is shown below.

<Window x:Class="WPF01.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPF01"
        mc:Ignorable="d"
        Title="My First WPF Program" Height="200" Width="300">
    <Grid Margin="0,0,0,0">
        <Button x:Name="mybutton" Content="Button" HorizontalAlignment="Left" Margin="40,20,0,0" VerticalAlignment="Top" Width="75" Click="mybutton_Click"/>
    </Grid>
</Window>

Here is the code behind.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

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

        private void mybutton_Click(object sender, RoutedEventArgs e)
        {  // double click the button on the Designer to get this
            MessageBox.Show("You clicked me!");
        }
    }
}

Series Navigation<< C# WPF IntroductionC# WPF without XAML – Window Class >>