Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Introduction to WPF

0.00/5 (No votes)
12 Sep 2008 1  
This tutorial shows you some of the basics of a WPF program, and shows you how to create a WPF Hello World application.

Downloads


What This Tutorial Teaches 

This tutorial teaches some the basics of WPF, and gives a springboard to other WPF concepts.

The End Result

At the end of this tutorial, you will have a simple WPF Hello World application.

The Tutorial 

A Little Bit About WPF 

WPF (Windows Presentation Foundation) was designed by Microsoft as a replacement for the aging WinForms API. WPF, along with three other components, WCF (Windows Communication Foundation), WF (Windows Workflow Foundation), and CardSpace make up the majority of new features in .NET 3.0.


Now, that we know a bit of background on WPF, let’s get started! First, create a new WPF application using File > New > Project. Select a WPF Application in C# and save it where you feel fit.
We’re first going to examine the code in the WPF Template.
<Window x:Class=WpfApplication1.Window1
    xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
    xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
    Title=Window1 Height=300 Width=300>
    <Grid>
        
    </Grid>
</Window>  
What the above does is creates our window, and places a grid in it.
This code is in XAML, an XML-like language used with WPF. Every tag can represent either an object, like a grid or a button, or a property not defined within the main tag. While that last part about the properties may sound confusing, worry not, as I’ll explain that in-depth later.
Now, let’s go ahead and create our first functional application, which (you guessed it) is a Hello World program.
Delete the Grid tags so the code looks like this:
<Window x:Class=WpfApplication1.Window1
    xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
    xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
    Title=Window1 Height=300 Width=300>
</Window>
Now, we’re going to add an object of the button class using this XAML. Add this code in your Window Tag:
<Button></Button>
This tag is equivalent to this C# code:
new Button();
Now, this C# code doesn’t actually create a button on screen, only instances a button class. We’d have to mess with some other stuff to get this on screen in the window. However, the underlying concept is the same.
Notice that there is no variable name associated with our new button. In XAML, we have to set an object’s Name property for the object to have a name.
With that said, we can come up with this code:
<Button Name=myButton></Button>
This is fundamentally equivalent to this C# code:
Button myButton = new Button(); 
Bear in mind that writing this XAML will actually create an object accessible in the associated C# code:
<Button Name=myButton></Button>
This means that when myButton is declared in the XAML, we can change its properties in our C# code, like this:
myButton.Background = Brushes.Black;
We can also set properties in XAML, like this:
<Button Background=Black></Button>
Now, let’s get back to our code. We’re going to create a button and set its Name property, and its click event handler, then have some C# code execute when we click the button.
Create a new button with the name HelloWorld, like this:
<Button Name=HelloWorld></Button>
Now, set the Click event handler to a new event. Type Click after the name property, and let Intellisense fill in this: Click=&quot;&quot; Now, let it make a new method for the event handler by clicking <New Event Handler>.
Now, your Button tag should look like this:
<Button Name=HelloWorld Click=HelloWorld_Click></Button>
Now, we’re going to fill in between the start and end button tags with the text on the button. Coding this would result in a button with the text “Hello, World!” on it:
<Button Name=HelloWorld Click=HelloWorld_Click>Hello, World!</Button>
There is also another way to set what is between tags. We can set the Content property to what we want inside the tags, as long as we don’t have any nested tags inside the main tag. This applies for normal properties, too. So, this would yield the same results as what we coded before:
<Button Name=HelloWorld Click=HelloWorld_Click Content=Hello, World!/>
Anyway, change it back, because we’re going to to a bit more with this button. Now, let’s experiment with the Background property:
<Button Name=HelloWorld Click=HelloWorld_Click Background=Gray>
    Hello, World!</Button>
This turns our button gray. However, we can apply more complex types of backgrounds, by expanding the Background property out into its own Button.Background tag. Consider the following:
    <Button Name=HelloWorld Click=HelloWorld_Click>
        Hello, World!
        
        <Button.Background>
            <LinearGradientBrush>
                <GradientStop Offset=0 Color=Black/>
                <GradientStop Offset=1 Color=Gray/>
            </LinearGradientBrush>
        </Button.Background>
    </Button>
Add this into your Window tag and hit F5 to run the program. You’ll notice that now you have a button with a gradient going from black in the upper-left corner, to gray in the bottom-right.
Let’s examine further. The Button.Background tag allows for one to add more complex and nested brushes (colors and things). The next nested tag, LinearGradientBrush defines a LinearGradientBrush. We can set more of its properties, like StartPoint and Endpoint, but those won’t be covered.
Inside the LinearGradientBrush tag are two GradientStops . Those are the colors used in the gradient. Experiment with adding another GradientStop. Why doesn’t it show up? It’s because we need to mess with the offsets a little. The maximum offset number to show equal parts of each color is 1, so we need to divide 1 (maximum offset number to show equal parts of each color) by 2 (there are three gradients, but the first shows no matter what the offsets are on the others). So this gives us increases of .5 for each GradientStop.Offset.
Your 3-gradient code will look like this:
     <Button Name=HelloWorld Click=HelloWorld_Click>
        Hello, World!
        
        <Button.Background>
            <LinearGradientBrush>
                <GradientStop Offset=0 Color=Black/>
                <GradientStop Offset=.5 Color=Gray/>
                <GradientStop Offset=1 Color=Antique White/>
            </LinearGradientBrush>
        </Button.Background>
    </Button>
Now, let’s stay with our original code with only two offsets. Let’s now start on the C# part. Right click on the start of the button tag, and click Navigate to Event Handler. Because we defined a Name property for our Button, we can access our Button by name, just like any other object. So, now we’re going to add some code that changes the button’s text and disables it. Add this in your HelloWorld_Click method:
HelloWorld.IsEnabled = false;
HelloWorld.Content = Clicked;
This should be pretty self-explanatory. It sets the IsEnabled property to false, disabling the button, and then sets to Content property to “Clicked”. Remember that the Content property is equivelent to whatever is between the main tags of an object, but not a tag nested in the main tag. Your final XAML should look like this:
<Window x:Class=WpfApplication1.Window1
    xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
    xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
    Title=Window1 Height=300 Width=300>
    
    <Button Name=HelloWorld Click=HelloWorld_Click>
        Hello, World!
        
        <Button.Background>
            <LinearGradientBrush>
                <GradientStop Offset=0 Color=Black/>
                <GradientStop Offset=1 Color=Gray/>
            </LinearGradientBrush>
        </Button.Background>
    </Button>
</Window>  

And your final C# should look like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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 WpfApplication1
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            
        }

        private void HelloWorld_Click(object sender, RoutedEventArgs e)
        {
            HelloWorld.IsEnabled = false;
            HelloWorld.Content = Clicked;
        }
    }
}
Thanks for reading, and more WPF tutorials are on the way!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here