You are on page 1of 11

Not quite what you are looking for?

You may want to try: PSAM WPF Control Library A Restaurant and Waiter helper app in WPF and Windows Mobile
9,210,424 members and growing! Email Password Sign in Join highlights off Lost password?



Quick Answers






introduction to wpf

Platforms, Frameworks & Libraries Windows Presentation Foundation General

WPF Tutorial : Beginning

By Abhishek Sur | 28 Dec 2010 | Article
C # .NET Dev WPF Intermediate

Licence First Posted Views Downloads Bookmarked

C POL 28 Dec 2010 96,788 3,339 196 times

Part of The WPF / Silverlight Zone sponsored by

See Also
More like this More by this author

The article will guide you through the basics of WPF programing with in-depth knowledge about the architecture and the working principles of WPF programs. The article finally creates a sample "Hello World" application to step you into a new foundation.
Article Browse Code Stats Revisions (3) Alternatives
4.76 (100 votes) 46

Download source - 24.97 KB

Table of Contents
Introduction Windows Presentation Foundation Features of WPF What is XAML? WPF Architecture Few things to Know before you proceed What is meant by Dispatcher & Thread Affinity? What is Visual Tree and Logical Tree? Why RoutedEvent? Why DependencyObject is Used? What about Hardware Acceleration and Graphics Rendering Tiers in WPF? Object Hierarchy Building Your First WPF Application Conclusion

Hot News: Windows 8 review: Yes, it's that bad The C ode Project Insider. Free each morning.

After working for more than 6 months in WPF, it is time to start writing on the basics of WPF. I have already put up a few articles on this topic, which basically deal with some specific problems. Now it is time to go beyond that, and to let you understand how / why WPF came to us as a revolution to UI development. As this is an article for beginners to intermediate level programmers, I will try to give as many basic examples as I can. I will also put a few reference links to each article of the series to make you navigate the other articles easily. WPF WPF WPF WPF WPF WPF WPF Tutorial Tutorial Tutorial Tutorial Tutorial Tutorial Tutorial : : : Beginning [^] Layout-Panels-Containers & Layout Transformation [^] Fun with Border & Brush [^] TypeConverter & Markup Extension [^] Dependency Property [^] Concept Binding [^] Styles, Triggers & Animation [^]

Windows Presentation Foundation

Related Articles
Introduction to Attached Behaviors in WPF Introduction to WPF Introduction to WPF Templates Introduction to the WPF DataGrid WPF Introduction: Databinding +


Styles + IValueC onverter Introduction to C omposite WPF (C AL, Prism): Part 1 Introduction to C omposite WPF (C AL, Prism): Part 2 Introduction to WPF Data Binding Introduction to D3DImage An Introduction to Silverlight Introduction to wxWidgets - 2. RavenDB - An Introduction Introduction to Anthem.NET Introduction to .NET Introduction to NLog Introduction to wxWidgets WC F by Example - Introduction SilverLight Introduction XLINQ Introduction Part 3 Of 3 Introduction to WF (Part01) LINQ Introduction Part 1 Of 3

As the name says all, WPF is actually a new framework introduced with .NET framework 3.0 which actually puts forward a new set of classes and assemblies which allow us to write programs more efficiently and flexibly. It uses Direct3D rendering which employs graphics cards to render the output on the screen. Thus the drawing in the form will be smooth and also there is a chance to utilize the hardware capabilities installed in your machine. In case of traditional GDI forms application, it is not possible to use advanced graphics capabilities and hence Windows Forms application will always be inefficient in comparison to WPF. Another important thing that I must address in this regard, GDI Windows forms application uses Operating system controls to build its application. Thus it is basically very hard to customize them in your own application. WPF controls are actually drawn over the screen, and hence you can customize controls totally and modify their behavior when required.

Features of WPF
WPF comes with lots of advantages. Let me introduce a few of its features: Device Independent Pixel (DPI) WPF introduces Device Independent DPI Settings for the applications built with it. For a window, it is very important to calculate how many Dots Per inch(DPI) the screen could draw. This is generally dependent on the hardware device and operating system in which the application runs and also how the DPI settings is applied on the Device. Any user can easily customize these settings and hence make the application look horrible. Windows forms application uses pixel based approach so with changing DPI settings, each control will change its size and look. WPF addresses this issue and makes it independent of DPI settings of the computer. Let's look at how it is possible:

Let's say you have drawn a box, just like the one in the figure, which is 1 inch long in 96 dpi screen. Now if you see the same application in 120 dpi settings, the box will appear smaller. This is because the things that we see on the screen are totally dependent on dpi settings.


In case of WPF, this is modified to density based approach. That means when the density of pixel is modified, the elements will adjust them accordingly and hence the pixel of WPF application is Device Independent Pixel. As you can see in the figure, the size of the control remains the same in case of WPF application and it takes more pixels in case of 120 DPI application to adjust the size properly. Built-In Support for Graphics and Animation : WPF applications as being rendered within DirectX environment, it has major support of graphics and animation capabilities. A separate set of classes are there which specifically deal with animation effects and graphics. The graphics that you draw over the screen is also Vector based and are object oriented. That means, when you draw a rectangle in WPF application, you can easily remove that from the screen as rectangle is actually an object which you always have a hold on. In a traditional Windows based application, once you draw a rectangle, you can't select that individually. Thus programming approach in case of WPF is completely different and more sophisticated than traditional graphics approach. We will discuss graphics and animation in more detail in a later section of the article. Redefine Styles and Control Templates In addition to graphics and animation capabilities, WPF also comes with a huge flexibility to define the styles and C n r l e p a e . Style based technique as you might come across with CSS is otoTmlts a set of definitions which defines how the controls will look like when it is rendered on the screen. In case of traditional windows applications, styles are tightly coupled with each control, so that you need to define color, style, etc. for each individual control to make it look different. In case of WPF, Styles are completely separated from the U E e e t Once you define a style, you can Ilmn. change the look and feel of any control by just putting the style on the element. Most of the U E e e t that we generally deal with are actually made using more than one Ilmns individual elements. WPF introduces a new concept of T m l t s which you might use to epae, redefine the whole control itself. Say for instance, you have a C e k o , which has a hcBx R c a g e in it and a C n e t r s n e (one where the caption of the T x B x appears). etnl otnPeetr eto Thus you can redefine your c e k o and put a T g l B t o inside it, so that the check will hcbx ogeutn appear on the T g l B t o rather than on the R c a g e This is very interesting. We will ogeutn etnl. look into more detail on S y e and C n r l e p a e in later section of the article. tls otoTmlts Resource based Approach for every control Another important feature of WPF is Resource based approach. In case of traditional windows applications, defining styles is very hectic. So if you have 1000 buttons, and you want to apply Color to each B t o sto Gold, you need to create 1000 objects of Color and assign each to one utn individual elements. Thus it makes it very resource hungry. In WPF, you can store styles, controls, animations, and even any object as resource. Thus each resource will be declared once when the form loads itself, and you may associate them to the controls. You can maintain a full hierarchy of styles in a separate file called R s u c D c i n r , from which styles for the whole application will be applied. Thus WPF eoreitoay application could be themed very easily. New Property System & Binding Capabilities In the next step, I must introduce the new property system introduced with WPF. Every element of WPF defines a large number of dependency properties. The dependency properties have strong capabilities than the normal properties. Thus when I define our new property, we can easily register my own property to any object I wish to. It will add up to the same observer that is associated to every object. As every element is derived from D p n e c O j c in its object eednybet hierarchy, each of them contains the Dependency Observer. Once you register a variable as Dependency property, it will create a room on the observer associated with that control and set the value there. We will discuss this in more detail in later sections of the series.

What is XAML?
According to the definition, XAML is an XML based declarative markup language for specifying and setting the characteristics of classes. In other words, XAML is a language used by WPF, Silverlight or any other application which can declare classes by itself. So, you can declare a variable, define the properties of any class and directly use it in your application. The XAML parser will automatically parse and create the actual object while it renders the application. XAML is generally used to define layout of UI, its elements and objects for static and visual aspect. We cannot define flow of a program using XAML. So even though there are large capabilities of XAML, it is actually not a programming language, rather it is used to design UI of the application. Thus XAML employs other programming languages like C#, VB.NET, etc. to define the logic in code behind.

E p e s o B i d r is the best tool to generate XAML. xrsinule

WPF Architecture
For every new technology, it is very essential to have a clear idea about its architecture. So before beginning your application, you must grab a few concepts. If you would not like to know WPF in detail, 3/11

please skip this section. As mentioned earlier, WPF is actually a set of assemblies that build up the entire framework. These assemblies can be categorized as: Managed Layer UnManaged Layer Core API Managed Layer: Managed layer of WPF is built using a number of assemblies. These assemblies build up the WPF framework, communicate with lower level unmanaged API to render its content. The few assemblies that comprise the WPF framework are: 1. PresentationFramework.dll: Creates the top level elements like layout panels, controls, windows, styles, etc. 2. PresentationCore.dll: It holds base types such as U E e e t Visual from which all shapes and Ilmn, controls are Derived in PresentationFramework.dll. 3. WindowsBase.dll: They hold even more basic elements which are capable of being used outside the WPF environment like D s a c e object, D p n e c Objects. I will discuss each of ipthr eedny them later. Unmanaged Layer (milcore.dll): The unmanaged layer of WPF is called milcore or Media Integration Library Core. It basically translates the WPF higher level objects like layout panels, buttons, animation, etc. into textures that D r c 3 expects. It is the main rendering engine of WPF. ietD WindowsCodecs.dll: This is another low level API which is used for imaging support in WPF applications. WindowsCodecs.dll comprises a number of codecs which encode / decode images into vector graphics that would be rendered into WPF screen. Direct3D: It is the low level API in which the graphics of WPF is rendered. User32: It is the primary core API which every program uses. It actually manages memory and process separation. GDI & Device Drivers: GDI and Device Drivers are specific to the operating system which is also used from the application to access low level APIs.

In the above figure, you can see how different framework elements communicate between one another that I have just discussed.

Few Things to Know Before You Proceed

There are quite a few things that you must know before starting with WPF applications.

What is Meant by Dispatcher & Thread Affinity?

When WPF application starts, it actually creates two threads automatically. One is Rendering Thread, which is hidden from the programmer, so you cannot use the rendering thread directly from your program; while the other is Dispatcher Thread, which actually holds all the UI elements. So in other words, you might say Dispatcher is actually the UI thread which ties all the elements created within the WPF application. Conversely, WPF requires all the UI elements to be tied with Dispatcher thread, this is 4/11

called Thread Affinity. Thus you cannot change any element created on D s a c e thread from any ipthr other threads, thus it follows the same Win32 based APIs. Thus it allows you to inter-operate any WPF component into H N based API. For more, read this. [^] WD

D s a c e is a class that handles thread affinity. It is actually a prioritized message loop through ipthr which all elements are channeled through. Every U E e e tis derived from D s a c e O j c which Ilmn ipthrbet defines a property called D s a c e which points to the UI thread. Thus from any other thread, if ipthr you want to invoke or access UI component, you need to Invoke using D s a c e thread. ipthr D s a c e O j c actually has two chief duties, to check and verify if the thread has access to the ipthrbet

What is Visual Tree and Logical Tree?

Every programming style contains some sort of L g c l r e which comprises the Overall Program. The oiaTe L g c l r ecomprises the elements as they are listed in XAML. Thus they will only include the oiaTe controls that you have declared in you XAML.

V s a T e on the other hand, comprises the parts that make up the individual controls. You do not iulre generally need to deal with V s a T e directly, but you should know how each control is comprised iulre
of, so it would be easier to build custom templates using this.

I personally always like to see the V s a T e before using it. E p e s o B i d ris the one tool iulre xrsinule that allows you to generate the actual control.

Why RoutedEvent? R u e E e tis very new to the C# language, but for those who are coming from JavaScript/web tech, otdvn you would have found it in your browser. Actually there are two types of R u e E e t One which otdvn.
Bubbles through the Visual tree elements and another which Tunnels through the visual tree elements. There is also Direct R u e E e t which does not Bubble or Tunnel. otdvn

When a R u e event which is registered, is invoked, it Bubbles / Tunnels through the Visual Elements otd and calls all the Registered R u e E e t a d e s associated within the Visual Tree one by one. otdvnHnlr To discriminate between the two, WPF demarcated events with Preview*** as the events which are Tunneled and just *** for the events that Bubbles. For instance, I P e i w o s D w is the event srveMueon that tunnels through the Visual Child elements while M u e o n Bubbles. Thus Mouse Down of the osDw O t r o t element is called first in case of I P e i w o s D w while Mouse Down for the uems srveMueon innermost element will be called first in case of M u e o nevent. osDw

Why DependencyObject is Used?

Every WPF control is derived from D p n e c O j c . D p n e c O j c is a class that supports eednybet eednybet D p n e c P o e t , a property system that is newly built in WPF. Every object is derived from eednyrpry D p n e c O j c and hence it can associate itself in various inbuilt features of WPF like eednybet E e t r g e s P o e t B n i g , A i a i n , etc. vnTigr, rpryidns nmtos 5/11

Every D p n e c O j c actually has an O s r e or a L s and declares 3 methods called eednybet bevr it C e r a u , S t a u and G t a u which are used to add/edit/remove those properties. Thus laVle eVle eVle the D p n e c P o e t will only create itself when you use S t a u to store something. Thus, it eednyrpry eVle is resource saving as well. We will look at D p n e c P o e t in detail in other articles of the series. eednyrpry

What about Hardware Acceleration and Graphics Rendering Tiers in WPF?

Another important thing that you should know is how the WPF graphics is rendered. Actually WPF rendering automatically detects how much hardware acceleration is supported by the current system and adjusts itself accordingly. The graphics rendering detects the appropriate tier for rendering the output accordingly. For hardware rendering, few things that have most of the impact are: 1. Video RAM: This determines the size and number of buffers that the application might use to render its output. 2. Pixel Shader: It is a graphics utility which calculates effects on per pixel basis. 3. Vertex Shader: It is a graphics processing utility that performs mathematical calculations on Vertex of the output. They are used to add special effects to objects in 3D environment. 4. MultiTexture Blending: This is a special function that allows you to apply two or more textures on the same object in 3D. Now the rendering engine of WPF determines which tier is appropriate for the current application and applies the rendering tiers accordingly. 1. TIER 0: No graphics hardware acceleration takes place, rather everything is rendered using Software. Any version of DirectX 9 or less is capable of rendering this output. 2. TIER 1: Partial hardware and software rendering. You might use Directx9 or greater to use this tier. 3. TIER 2: Full hardware acceleration. Directx9 or above can render this output. To know more about it, refer here [^] .

Object Hierarchy
There are quite a few objects in any WPF control. Let's discuss one by one as in the figure. (The a s r c class is marked in ellipse while concrete class in Rectangles) : btat

D s a c e O j c : Mother of all WPF controls which takes care of UI thread ipthrbet D p n e c O j c : Builds the Observer for Dependency Properties eednybet V s a : Links between managed libraries and milcore iul 6/11

U E e e t Adds supports for WPF features like layout, input, events, etc. Ilmn: F a e o k l m n : Implementation of U E e e t rmwrEeet Ilmn S a e Base class of all the Basic Shapes hp: C n r l The UI elements that interact with the user. They can be Templated to change look. oto: C n e t o t o : Baseclass of all controls that have single content otnCnrl I e s o t o : Baseclass for all controls that show a collection tmCnrl P n l Baseclass of all panels which show one or more controls within it ae:

Building Your First WPF Application

Now the time has come to build your first WPF Application. To do this, let's open Visual Studio 2008 / 2010. For this example, I used Visual Studio 2008. Create a new Project. You will see a new window. The XAML will look like:
C ollapse | C opy C ode

<idwxCas"isWnosplcto.idw" Wno :ls=FrtidwApiainWno1 xls"tp/shmsmcootcmwnx20/alpeetto" mn=ht:/cea.irsf.o/if/06xm/rsnain xlsx"tp/shmsmcootcmwnx20/al mn:=ht:/cea.irsf.o/if/06xm" xNm=Wno1 :ae"idw" Tte"idw"Hih=30 Wdh"0" il=Wno1 egt"0" it=30> <rd Gi> <Gi> /rd <Wno> /idw

Here the blank window is produced. H i h / W d hrepresents the Size of the Window. Title egt it determines the text which is displayed in the T t e a of the window. Every control in XAML could be ilBr named with x N m attribute. This will be used to reference the W n o object in your XAML. x C a s :ae idw :ls attribute represents the class which should be associated with current W n o . As I already told you, idw that XAML is not self sufficient, so to define logic you need a class in C# or VB.NET.

G i is the primary layout for WPF application. G i can take multiple C i d elements. So let us put rd rd hl some controls into the g i . rd
C ollapse | C opy C ode

<rd Gi> <rdRweiiin> Gi.oDfntos <oDfnto Hih=At"/ Rweiiin egt"uo > <Gi.oDfntos /rdRweiiin> <rdClmDfntos Gi.ouneiiin> <ouneiiinMnit=5"/ ClmDfnto iWdh"0 > <ouneiiinWdh"uo / ClmDfnto it=At" > <ouneiiinWdh""/ ClmDfnto it=* > <Gi.ouneiiin> /rdClmDfntos <etlc Tx=EtrNm : Gi.o=0 Gi.oun""/ TxBok et"ne ae " rdRw"" rdClm=0 > <eto xNm=ttae Gi.o=0 Gi.oun""Mnit=5"> TxBx :ae"xNm" rdRw"" rdClm=1 iWdh"0/ <utnCnet"lc M"Gi.o=0 Gi.oun""Cik"utnCik/ Bto otn=Cik e rdRw"" rdClm=2 lc=Bto_lc"> <Gi> /rd

You can see that I have defined R w e i a i nand C l m D f n t o . This allows you to divide oDfnto ouneiain the grid into cells so that you can place your control exactly where you want to. For each R w e i a i nand C l m D f n t o , you can use H i h and W d h of it. You can see I oDfnto ouneiain egt it have used 5 , A t , and *as w d h A t represents the size which we would define for the control 0 uo it. uo during control definition. *indicates the rest of the space which it can take. Thus, you can see the button is spread the rest of the area of the column it finds. Now in the Behind, I put a M s a e o to show the content of T x B x esgbx eto.
C ollapse | C opy C ode

piaevi Bto_lc(betsne,RueEetrse rvt od utnCikojc edr otdvnAg ) { Msaeo.hwsrn.omt"i{}, esgBxSo(tigFra(H 0" hsttaeTx); }

Therefore you can see your name will be prompted to you. Isn't it funny. :) If you have noticed the XAML minutely, you might wonder how I can define the property of G i within rd 7/11

other controls. Like I defined G i . o = in each of the control. This is actually possible due to the rdRw0 use of Dependency properties. It's a new feature introduced with WPF. We will discuss in detail later on.

This is the first part of the series of WPF. This comprises the initial discussion of the WPF application. In the next articles, I would delve more into other aspects of WPF programs and how you can work with WPF controls and guide you to build a solution. Hope you like reading this post.

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Abhishek Sur Did you like his post? Oh, lets go a bit further to know him better. Visit his Website : to know more about Abhishek. Basically he is from India, who loves to explore the .NET world. He loves to code and in his leisure you always find him talking about technical stuffs. Presently he is working in WPF, a new foundation to UI development, but mostly he likes to work on architecture and business classes. ASP.NET is one of his strength as well. Have any problem? Write to him in his Forum. You can also mail him directly to Want a Coder like him for your project? Drop him a mail to Visit His Blog Dotnet Tricks and Tips

Web Developer Buildfusion Inc India Member Follow on Twitter

Dont forget to vote or share your comments about his Writing Article Top
Sign Up to vote Poor Excellent Vote

Comments and Discussions

You must Sign In to use this message board. Search this forum Profile popups Noise Medium Layout Expand Posts & Replies Refresh My vote of 5 ArunKS783 Per page 25 Go Update First Prev Next 23hrs 34mins ago

The best of tutorials i have come across on WPF, the example is small and understandable. The reasons given and the ability to strike to point is awesome.
Sign In View Thread Permalink My vote of 5 Eric Fan 19:25 21 Aug '12

Excellent post
Sign In View Thread Permalink My vote of 5 johannna 0:01 10 Aug '12

This one is simply perfect for a beginner like my to get accustomed with wpf! Thank you!



Sign In View Thread Permalink My vote of 1 Syed Javed 20:38 24 Jul '12

Good one...
Sign In View Thread Permalink Re: My vote of 1 Abhishek Sur 0:23 10 Aug '12

Good but you still voted poor (1)...

Abhishek Sur
Don't forget to click "Good A nswer" if you like this Solution.

Visit My Website-->

Sign In View Thread Permalink Re: My vote of 1 Syed Javed 0:54 10 Aug '12

I think this was a mistake. I clicked one insted of 5 after typing my comments
Sign In View Thread Permalink Re: My vote of 1 Abhishek Sur 1:32 10 Aug '12

Yes. You can revote to change.

Abhishek Sur
Don't forget to click "Good A nswer" if you like this Solution.

Visit My Website-->

Sign In View Thread Permalink its Expression Blend , not ExpressionBuilder usamakhalil 16:24 17 Jul '12

Hi, you have mistakenly mentioned ExpressionBuilder to generate XAML. its Expression Blend.
Sign In View Thread Permalink My vote of 5 zclmoon 0:16 11 Jul '12

Very Userful, Thanks.

Sign In View Thread Permalink My vote of 5 Madhan Mohan Reddy 23:00 26 Jun '12

Sign In View Thread Permalink My vote of 5 anbarasuarsh 21:21 17 Jun '12

easily understandale
Sign In View Thread Permalink My vote of 4 Aditya_Srivastava 18:57 15 Apr '12

Really good for beginners...

Sign In View Thread Permalink My vote of 5 sepidar_902 4.00/5 (1 vote) 0:16 8 Apr '12

thanks a lot ... very good for beginners


Sign In View Thread Permalink My vote of 3 mungflesh 6:08 23 Mar '12

This doesn't get to the point. Who has the time to read this waffle?
Sign In View Thread Permalink My vote of 5 CarstenV2 1.00/5 (3 votes) 9:06 17 Jan '12

Nothing to say - excellent!

Sign In View Thread Permalink ExpressionBuilder where can it be Avi Farah 6:09 12 Oct '11

Abhishek, Outstanding article. Qtn: where will I b able to download ExpressionBuilder from? Thx, Avi
Sign In View Thread Permalink Re: ExpressionBuilder where can it be Abhishek Sur 9:14 12 Oct '11

Here you go.[^]

Abhishek Sur
Don't forget to click "Good A nswer" if you like this Solution.

Visit My Website-->

Sign In View Thread Permalink it is great araelec

5.00/5 (1 vote) 23:19 2 Oct '11

hi it is so great,thank you
Sign In View Thread Permalink My vote of 5 eg_Anubhava 19:19 1 Sep '11

Nice One
Sign In View Thread Permalink My vote of 4 Raghaav 5:15 27 Jun '11

Good one...
Sign In View Thread Permalink My vote of 5 korova2000 5.00/5 (1 vote) 6:41 15 Jun '11

I like it! Very good

Sign In View Thread Permalink My vote of 5 santoshng 5.00/5 (1 vote) 23:13 19 May '11

excellent for beginners

Sign In View Thread Permalink 5.00/5 (1 vote)

My vote of 3


1:01 24 Apr '11

Very good article for new commer.

Sign In View Thread Permalink My vote of 5 James Schuldiner 3:40 17 Apr '11

* easy to read and understand; * good summary of all the essential elements;


Sign In View Thread Permalink My vote of 5 digbyd 0:40 4 Apr '11

Nice bit of background with a simple example.

Sign In View Thread Permalink Last Visit: 23:34 21 Aug '12 General News Last Update: 16:32 24 Aug '12 Suggestion Question Bug Answer Joke Rant 1 2 Next Admin

P ermalink | A dvertis e | P rivac y | M obile Web0 1 | 2 .5 .1 2 0 8 2 0 .2 | L as t U pdated 2 8 D ec 2 0 1 0

L ayout: fixed | fluid

A rtic le C opyright 2 0 1 0 by A bhis hek Sur E verything els e C opyright C odeP rojec t, 1 9 9 9 - 2 0 1 2 T erms of U s e