Tuesday 28 August 2007

WPF "Hello, World"

So I managed to complete the WPF introduction course which I last posted about and after doing this I thought I would like to create a simple application using XAML and WPF to feel a little more at home with the whole subject, so I decided to download me a copy of Orcas Beta 2 Express and create a Hello World App.

Hello World applications are normally the first application (if you can even call them that) that most people will make when they start looking at a new programming language or programming concept. So heres how I went about creating my first WPF application.

I used Orcas, which is really nice I love the split layout that is used to display the design in the top half of the screen and the XAML code in the bottom section, this reminds me of using Expression Web and how the design and code is split on a single screen making it easy to tweak little bits of the program without constantly switching to a code view. However to see the code behind file for the application (much like the code behind files in ASP.NET) you have to open a new tab to get to this.

So getting started I just dragged and dropped a button and text box onto the form, this like i said before generates the XAML in the bottom half of the screen, so you can see how buttons are made in XAML. The XAML is really easy to understand and if like myself you have had some previous experience with XML you will find it pretty straigh forward.


Once I have my form layout how I want it, I then have to get the XAML button to respond to an event, this can either be done just like in a C# windows application by double clicking on the button or it can be done in the XAML code itself. To add an on click event you simply add a "click" attribute to the button tag.


So we now have:

click = "button1_click"

added to the attribue list for the button tag.

The click attribute says that when the button is clicked go and find the event handler called button1_Click in the code behind file.


For this event handler in the code it is extremly simple to display the desired text in the text box done just how you would if you were using any other language.


private void button1_Click(object sender, RoutedEventArgs e)
{
textBox1.Text = "Hello, World";
}




This then just simply displays the text "Hello, World" in the text box we created in design view. Now we can run the code and see the amazing aplication in all its glory.


I am hoping to get a little time to play about with WPF before I have to start uni so hopefully will start to make some better appliations than this.

No comments: