So, I wanted to do something a bit fresher and possibly more interesting for TD#5. I have been cramming a lot for my next MS exam of late, so wanted to just have some fun and not really think about anything :)
I therefore scanned my Tech ToDo list and and through I would go for WPF. Silverlight is quite high on my list, so I thought it would be good to get a high-level look at WPF in general (since I have not yet worked with XAML).
So, let’s rock and roll!
Getting Started/Initial Setup
I also use O’Reilly Safari, so I had a look on there for any WPF books. I came across Pro WPF in C# 2008 (Matthew MacDonald), so I added that to my library and began reading while nomming down on my breakfast.
As always, there is some sample code for the tech day, not much for this one that is really functional since I am really playing with some basic ideas.
Let’s crack on and see what I learned!
Once I had created the WPF application I thought I would take a look at what the project template had churned out for us. These really look very similar to a basic WinForms application. You get an “App.xaml” which is the same idea as “Program.cs” (essentially the bootstrap for the application). This will be the entry point for the application which will spin up the code that we implement.
Obviously there are some different references in our project. Remember that WPF is a completely different rendering engine to WinForms. While you will see that some of the concepts are similar (Brushes and the like) it is actually a completely different code set and hierarchy. Similar to WebForms vs. MVC – we still have the power of the .NET Framework itself, just a different way or processing things high up in the UI tier.
In Pro WPF in C#' 2008 (from now on “the book”) it was very clear from the outset that the layout model is very different to what we are used to in the WinForms world. Layout in WPF is designed to be flexible and flowing. This means (for the most part) “bye bye Top and Left”. Rather than defaulting to a fixed size/co-ordinate system WPF works around we use a more web-like document flow where we specify sizes and margins and let the rendering engine sort it out.
I thought I would be worried once I sat down with the XAML since I thought “great, another language to learn”. Thankfully, I was incorrect in this assumption. Those of us that have worked/work with ASP.NET should be pretty comfortable with XAML since we are used to the way markup is parsed and used to spin up actual objects that do things. Those from WinForms may find it a little alien at first, but you should get the hang of it pretty quick. Just think “new” when you see “<”. For example:
Could equate to the following C#:
Once you get your head around the fact that markup can actually do stuff (as opposed to pretty dumb HTML) it' becomes pretty straight forward.
I also found that a fair few of the controls follow the Attached Properties model. Normally, in order to make controls work together you may need to start messing with code at both ends as well as alter the way in which the controls are initialised.
For example, lets say we had a control that adds sprinkles to other controls, we may need to controls to it to get the sprinkles added to it:
While this may look fine, what if we were producing a page that had 1000 donuts that all needed sprinkles? We would suddenly need to start creating lots of spinklers which could be expensive. Not to mention the fact that we may actually want to put the donuts in a DonutBox!
Now, lets think about this, of course the sprinkler needs to know about the donut(s) we want to sprinkle, but do we need to “put the donuts in the sprinkler” (logically rather than physically)?
Consider the following:
See the difference? We just added a “Sprinkler” property to the donut classes that takes a Sprinkler, right?
The properties are actually added to the donut controls by the Sprinkler. This is very similar to the Extender Provider model employed in WinForms (e.g. the ToolTip Component). This enables us to create controls that extend other classes/controls in a non-obtrusive and clean way. Attached Properties are an improvement over Extender Providers since the methods called are static you don’t need to actually have an instance of the class floating around.
What’s really cool is that you would then think that the Sprinkler is somehow maintaining a list of the donuts it is sprinkling, right? Possibly, but it doesn’t need to because the donuts themselves actually store the property value. This is because all controls derive from DependencyObject.
I was really pleased to see that User Controls are just as quick and easy to create in WPF. These are much the same as Win/WebForms User Controls with the obvious difference being that the designer works with XAML.
One thing I would note is that since the layout of WPF applications is a bit more dynamic and free-flowing, I would suggest testing your controls thoroughly in a number of different host forms to ensure everything looks good when resizing etc.
Even though I have not really produced much in the way of an “application” at this point (as in something that performs a function/fulfils a purpose) I didn’t really feel like WPF would be that much more of a mystery to me. I am more than capable of Google’ing for specific details on certain controls etc. I therefore thought I would spend a bit of time playing with some of the cooler things that WPF has to offer. Animation is obviously a big part of this.
When I first started looking at animation, I did get a bit confused I think this may be because a few of the articles I came across were really not very good at breaking things down. I will do my best to explain the animation to you in a way that means you don’t have to go back to Google like I did :)
Imagine you are creating a reel of film. You have a ton of smaller film strips spliced up and you want to tape them all together in one kick-ass movie. Think of the Storyboard as the thing you are taping them to.
The Storyboard orchestrates a sequence of animations for you. Animation sequences are added to a Storyboard and then you (as the director of course) shout “Action!” and the sequence starts rolling.
So, before we do anything, we must create a Storyboard:
Now we take a break and grab a coffee after all that code.
Let’s say for sake of argument our animation of choice is the good old “fade out”. Traditionally in WinForms we would probably add a Timer to the form and then tell it to reduce a Controls opacity on each Tick, but surely there is a cleaner, smarter approach with WPF?
Indeed there is. Opacity is a property of the “double” type. So what we really need is something to wrap up the Timer and reduction of a double value over time. Enter the DoubleAnimation. This is exactly what he doctor ordered and exactly how animation is done in WPF. We manipulate the properties of controls over time to animate it.
Creates a animation that can be used to alter a double value from 1.0 to 0.0 over one second.
Sounds Great – I Can Still See the Control Though?
Of course, we have not actually bound it to a property of a control yet! All we created was the logic of the “fade” (reduction in opacity over time).
We have a few things to note here:
- There are two calls to static Storyboard methods.
- There is then a single call to an instance method.
- We have introduced something called a PropertyPath.
The PropertyPath is basically a roadmap to a property value. What we are doing in the code is pretty simple:
- Setting the high-level target for the animation to the Control by using it’s Name property.
- Setting the actual property for manipulation by creating a PropertyPath.
- Adding the animation to our main storyboard instance.
MAKE IT SO!
Right, we have now actually create all that is required to fade out a control. All we need to do is fire off the process with this (rather large) code snippet:
The storyboard will then do it’s job and execute the animations it contains.
One thing I really like about the above code (not sure if you noticed) is that there are no direct references required. Animations are very generic so we could easily wrap up the “FadeOut” code into something like:
We can then simply fade out control using:
Animations and Multithreading
After completing the above I thought I would see what it would be like to have a control fade out and then actually be removed (so controls reflow and reposition to fill its space).
This then ran me in to a problem which I think is important so I will quickly cover it here:
Animations run in a separate thread to the main application.
And rightly so, if they did not, your UI would freeze up while a control fades out. Sexy UI’s are great provided they do not come at a productivity cost. Fade outs are cool but would quickly piss me off if I lost minutes every day waiting for a control to fade out slowly.
In wanting to complete my goal I added code like:
Which seems fine at a quick glance, but now think about the animation running in a separate thread. When this is executed, the animation will begin, but the main thread of execution will continue, removing the control from the Window. So, the nice animation will start but then the control quickly disappears.
This can be solved by hooking up to the Storyboard.Completed event like so:
You can then remove the control from the Window in the event handler:
I had a lot of fun with this tech day, was nice to be working with something fresh while being rebellious and doing something that is to do with my next exam :) I personally have the feeling that the WPF team took a lot of lessons learned from WinForms and then brought some great stuff to the table to bring about a real nice platform to work on.
My only (at time of writing!) peeve is with the designer, why-oh-why is there no Events list in the properties Window?! If I just want to browse the Events I need to either go to MSDN or scan through a massive Intellisense list! Silly!
I hope those of you getting started with WPF in your own Tech Days/study got something of use out of this post!
Oh, I almost forgot. You may be thinking “not a lot of code for a whole day, Rob” – you would be correct.. I actually started playing with a new WPF-based project – more may follow soon :)