Flex and WPF: A comparison – Part 3a

In this installment of the comparison posts I will look at the Animation framework in WPF and Flex. Both these technologies have vastly simplified the programming model for doing animations on your User Interface. Both of them allow animations to be created using markup (XAML/MXML) or code (C#/AS3). There are a number of animations that can be used out-of-the-box and you can also create your own custom animations.

Since this part is again pretty long, I am splitting it into 2 subparts. In this subpart I’ll cover the way it is done in WPF.


Animations in WPF are typically created using Storyboards. Storyboards are timeline-based animations that run for a specific period of time and target specific elements on the UI. Let’s look at the XAML for a simple Storyboard that fades an Ellipse from opaque to transparent in one second.






Storyboard.TargetName=”e1″ From=”1″






The Storyboard.TargetName and Storyboard.TargetProperty target the property of the UI element that needs to be animated (in our case the Opacity property of Ellipse). We are using a DoubleAnimation because the Opacity property is of type double. The From, To and Duration values should be self-explanatory. Note that the format of the Duration property is HH:MM:SS.

More than one animation at the same time

The Storyboard class actually derives from ParallelTimeline, which means you can put multiple DoubleAnimations inside your Storyboard and all of them will animate in parallel. So if you wanted to move the Ellipse from x=100 to x=400 and also fade it out, you could so something like this:



Storyboard.TargetName=”e1″ From=”1″


Storyboard.TargetName=”e1″ From=”100″


Note how I added an extra DoubleAnimation to do the translation. It will now animate in parallel with the fading animation.

Playing in sequence

What if you wanted an animation to start only after the previous one has completed? Sure, you can do it using the BeginTime property. In the previous example if we wanted the translate animation to happen after the fade completes we can do it this way:



Storyboard.TargetName=”e1″ From=”1″


Storyboard.TargetName=”e1″ From=”100″



Note that since my BeginTime has been set to “0:0:1”, it will only start after the fade-animation completes. So the total time-length of the storyboard is 2 seconds as opposed to 1 second for the previous storyboard. You can also nest ParallelTimelines and mix and match with BeginTime to achieve pretty much any sequence of animations.

There are also other properties on the XXXAnimation classes (XXX denotes the type like Double, Color, etc) like

  • AutoReverse – which automatically reverses the animation
  • RepeatBehavior – which sets the number of times you want to repeat the animation. RepeatBehavior=”Forever” results in non-stop animation.
  • AccelerationRatio, DecelerationRatio – easing in/out values specified as a fraction of the Duration. AccelerationRatio=”0.25″ will accelerate the animation in the first quarter followed by constant-speed animation for the remaining 3/4th.

Using keyframes

The animations I described earlier were of the From/To kind, where you have a starting value and an ending value. If you wanted the animation to pass through multiple states in between the start and end values, you need to use keyframe animation. Here is an example right out of the Windows SDK with the comments explaining exactly what I want to convey!







<!– Animate from green to red using a linear key frame, from red to

yellow using a discrete key frame, and from yellow back to green with

a spline key frame. This animation repeats forever. –>






<!– Go from green to red in the first 2 seconds. LinearColorKeyFrame creates

a smooth, linear animation between values. –>

KeyTime=0:0:2 />

<!– In the next half second, go to yellow. DiscreteColorKeyFrame creates a

sudden jump between values. –>

KeyTime=0:0:2.5 />

<!– In the final 2 seconds of the animation, go from yellow back to green. SplineColorKeyFrame

creates a variable transition between values depending on the KeySpline property. In this example,

the animation starts off slow but toward the end of the time segment, it speeds up exponentially.–>

KeySpline=0.6,0.0 0.9,0.00 />




The keyframe animation classes follow the same naming convention of XXXAnimationUsingKeyFrames, where XXX is the type. In the above example we are using ColorAnimationUsingKeyFrames but you could also use DoubleAnimationUsingKeyFrames when animating properties of type Double.

Creating Custom animations

For most cases you should be able to get away with the default animation classes. However for some cases you do need to create your own animation classes. I did a blog post sometime back detailing this technique. The basic idea is that you have a <Type>AnimationBase class from which you derive your animation class, for eg. DoubleAnimation derives from DoubleAnimationBase. Inside the <Type>Animation class you override the CreateInstanceCore() Factory method that returns an instance of <Type>Animation. You can also define additional DependencyProperties on your animation class for further customization. The blog post I mentioned has all these details.

So Storyboards are pretty much the defacto way of describing animations in WPF. However you could also use DoubleAnimation or other animation classes directly without nesting inside a Storyboard. In my experience I have always found it best to have it inside a Storyboard. All the event-based triggering of animations consume Storyboards instead of <Type>Animation instances. I have skipped the part about creating Storyboards and animations in code but it is not much different. Since the tag-names map directly to the class-names, you could recreate the same object hierarchy in code.

The next post will be about Effects – the Flex way of doing animations!

Flex and WPF: A comparison – Part 2b

In part-2a we saw some of the building blocks of WPF and how they are used to achieve the content-style separation. This post is a continuation and will focus on Flex’s approach.

Flex has adopted the web standards right from ground up. So if you are a web developer who has had any experience with HTML, CSS, Javascript it should be very natural to program in Flex. A direct one-one mapping looks like this:



Javascript –> Actionscript


MXML markup + code-behind

    MXML is the markup language that is used to describe the User Interface components in Flex. In concept it looks very similar to XAML, but since it is also like HTML, it has the familiar tags like <mx:Script/> and <mx:Style/>. The <mx:Script/> tag is used for inline code-behind whereas the <mx:Style/> describe the stylesheet elements for the UI elements. In a previous post I did a comparison of the code-behind models in Flex and WPF, which is slightly more detailed. Actionscript is the language used for the code-behind and its syntax is very similar to Javascript.

    The standard practice for describing UIs is to use MXML. Even the event-handlers are specified directly inside MXML. However it is also possible to bypass MXML completely and define the UI component completely in Actionscript. In the former approach, the MXML compiler will generate the Actionscript for you, which in turn gets compiled to SWF.


    Databinding is definitely my favorite feature in Flex and it is extremely powerful. It is also very easy to make your model objects bindable by including a simple metadata tag like [Bindable] against the model property or object. This is simpler than the WPF approach where you will have to implement the INotifyPropertyChanged interface for the model object and manually fire the property change notifications. In Flex just by attaching the [Bindable] metadata tag you get FREE property change notifications. Of course if you want to customize the notifications, that too is possible. What I find really interesting is the part where you bind a UI element to a model object. Say I want to bind the text property of a <mx:Label/> to the firstName property of the Person object. The syntax would look something like this:



    var _person:Person = new Person(“Pavan”, “Podila”);



    <mx:Label text=”{_person.firstName}”/>



Since I made the _person instance [Bindable], the Label will automatically update its text property whenever _person.firstName changes. What is exciting is the fact that the curly braces syntax for data-binding can actually include Actionscript inside it! This is very useful in cases where I want to do a little bit of more formatting to the text. If I wanted my text to appear like “FirstName: PAVAN”, I could do this right inside the {}:

    <mx:Label text=”FirstName: {_person.firstName.toUpperCase()}“/>

Doing the same in WPF would have required me to write a class that implements the IValueConverter and then pass in the instance of my model as a parameter. So the syntax would look like below.

[Note that I am following the C#/XAML naming conventions, so my property names have the first letter of each word capitalized: FirstName, LastName.]


    <local:StringToUpperCaseConverter x:Key=”stringConverter”/>

    <local:Person x:Key=”person” FirstName=”Pavan” LastName=”Podila”/>


<Label Content=”{Binding Path=FirstName, Converter={StaticResource stringConverter}}”/>

Also my converter class would look like this:

    [ValueConversion(typeof (string), typeof (string))]

    public class StringToUpperCaseConverter : IValueConverter


        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)


            string firstName = (string)value;

            return “FirstName: “ + firstName.ToUpper();



        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)


            return null;



That definitely is a lot more typing to do than the Flex’s approach. I see this is as a major benefit in Flex which I would love to have in WPF.


MXML components

    MXML components are reusable views in your application. Say you have a photo-viewer application that shows a list of photos. Each photo could be wrapped inside a MXML component that shows other information about the photo when you click on it. The view of the photo and the interaction can be captured inside this component and can be reused throughout your application. These components can also behave like the DataTemplates in WPF. You can create a property on the MXML component and set that as the model object. Inside the component you can data-bind to the properties of the model thus simulating the DataTemplate. Note that the property you create on your MXML component is your DataContext.

    ItemTemplates in WPF have a direct one-one mapping with the ItemRenderers in Flex. List based controls use the ItemRenderers to render each item in the list. Here is a simple example of an inline ItemRenderer.

<mx:DataGridColumn headerText=”Online” dataField=”online”>



<mx:CheckBox click=”data.online=!data.online” selected=”{data.online}”/>





You can also create a separate MXML file, say Checkbox.mxml, that encapsulates the component. In that case you provide the name of the component to the itemRenderer property (itemRenderer=”Checkbox”, assuming Checkbox.mxml is in the same directory).

CSS styles, skins

    Styling a Flex application means creating a CSS file (or a group of CSS files) that provides the appearance for the different UI elements. Most CSS files would include customized values for many of the UI element properties. But if you want more fine-grained control on the appearance one can also create something called the Skins. A skin file is also a CSS file but can include components from a compiled SWF file. The SWF may have custom rendered skins, also called programmatic skins. Here is a nice article on creating skins for Flex.

Packaging into SWC, SWF and modules

    SWF is the final version of a compiled Flex application. It may also have a bunch of dependencies on Actionscript/Component libraries. These libraries are compiled as SWC. The other option for packaging is to use Flex Modules. Bruce Phillips did a good post on this topic and covers all the necessary material.


Technorati tags: , , ,

Code behind in Flex and WPF

I should really have posted about Part 2b of my comparison of Flex and WPF, but I wish to jump ahead a little and compare the code-behind model in Flex and WPF. I am doing this because of a post I saw on Ted Patrick’s blog. Ted mentions about the code-behind model in Microsoft technologies like ASP.Net and shows how you can replicate that model in Flex. ASP.Net introduced the term Code-Behind with its first release and it has become a standard way of keeping the logic separate from the UI. It is a common theme across many MS technologies including WinForms and WPF. The code-behind model follows some file-name conventions which makes it easy for Visual Designers (think VS2005) to automatically keep the UI and the code-behind in sync.


Let’s take the case of the visual designer (either Expression Blend or Cider) for WPF. Since WPF uses XAML to describe the UI, the markup is kept inside <your-component>.xaml. The corresponding code-behind is separated out into <your-component>.xaml.cs. The code-behind is linked in the XAML file with the x:Class attribute on the root-tag. The code-generation part of the designer merges the xaml and the code-behind to create a single intermediate C# file. This file is named as <your-component>.designer.cs. This file is auto-generated and not meant for manual editing. The .designer.cs file is used for compiling to a .Net Type inside your application’s assembly. WPF is very strict about these naming conventions and also enforces the separation of UI and code-behind in separate files. In the earlier CTP releases of WPF it was possible to have inline C# code inside the XAML (using CDATA sections). However that feature has been removed from the RTM release.

In Flex…

Flex provides both the WPF style of code-behind (ie. Separate MXML and AS files) and the inline AS with the <mx:Script/> tags. This model is natural because Flex is using the standard HTML + CSS + Javascript paradigm of development. I think that makes it very flexible and it leaves to the developers to decide what is the appropriate model for them. I think most apps will use a mixture of these two approaches. Sometimes it makes sense to keep the code inline with the MXML (say for easier maintenance) and on some occasions when the code is really large the separate code-file approach works best. Ted’s post talks more of the later approach.



Technorati tags: , , ,

Comparison of available choices for Enterprise RIA

Yakov Fain of Farata Systems does a great post comparing the various options for doing Enterprise RIA. Adobe Flex and WPF are on the list. I think we are starting to see a continuum form out of the available choices. On one end is the Rich Client Application space (Desktop) with WPF and on the other end we have plain HTML+CSS. In between we have Flash/Flex, WPF/E and AJAX.

The extremes are not always a good choice. Is it the middle ground? (Pun intended)


Technorati tags: , , ,

Flex and WPF: A comparison – Part 2a

In my earlier post I mentioned that both Flex and WPF do a separation of content from presentation. In the view of keeping the posts short, I am going to split Part 2 of the comparison into two subparts. In this first subpart I will only cover how WPF does the content-style separation. The next post will talk about Flex’s approach.

The WPF way

XAML markup + code behind

        Programming declaratively in XML is definitely more productive than writing plain code in C# or other .Net language. It helps in visualizing the structure of the UI without always relying on a tool. Plus editing and making changes is also easy. XAML or eXtensible Application Markup Language is the new XML based language for creating WPF UIs. One can describe the complete visual hierarchy of the UI in one or more XAML files. In fact it is also possible to add a lot of interactivity directly in XAML. Using data-binding we can connect UI elements together. For example I could connect the output of the Slider control to a Textbox. Complex animations can also be described in XAML using the <Storyboard/> tag and one can also hook up the animations to play when certain events happen – all in XAML. Of course not everything can be done declaratively, so where more fine grained control is needed, one can use the Code Behind class to describe the logic. A WPF application consists of an App.xaml file that describes the Application and a separate startup xaml file that is loaded when the application starts up. Have a look at this App.xaml file.

<Application x:Class=WindowsApplication1.App






Note how I specify the <Application/> and hook it up to the Code behind class using the x:Class attribute. The StartupUri points to Window1.xaml, which is the file that will be loaded when the application starts. Window1.xaml looks something like this:

<Window x:Class=WindowsApplication1.Window1








Since we are using the <Window/> tag, the application will create a standard Window control. Our Window is currently empty and has no UI elements and has a code-behind file linked with x:Class attribute. Note that by changing the StartupUri attribute of the <Application/> we can point to a different XAML file.


Templates – ControlTemplate, DataTemplate, ItemTemplate

    WPF does the content-style separation using Templates. With templates, it is possible to separate the behavior of the UI control from its presentation / appearance. For example, I could have a <Button/> control that doesn’t look like a Button but still behaves like one. This is possible by changing the default ControlTemplate of the Button to something else. Most UI controls in WPF, except for UserControls and Panels, have a Template property that provides the appearance for that control. The ControlTemplate is responsible for providing not only the appearance but also the behavior, eg. how the button reacts to a mouse-press, mouse-release, mouse-hover. They are specified using Triggers, which describe the appearance when the control is in a certain state.

<ControlTemplate TargetType={x:Type Button}>





Background={StaticResource NormalBrush}

BorderBrush={StaticResource NormalBorderBrush}>








<Trigger Property=IsKeyboardFocusedValue=true>

<Setter TargetName=BorderProperty=BorderBrush

Value={StaticResource DefaultedBorderBrush} />


<Trigger Property=IsMouseOverValue=true>

<Setter TargetName=BorderProperty=Background

Value={StaticResource DarkBrush} />


<Trigger Property=IsPressedValue=true>

<Setter TargetName=BorderProperty=Background

Value={StaticResource PressedBrush} />

<Setter TargetName=BorderProperty=BorderBrush

Value={StaticResource PressedBorderBrush} />




Similarly we have DataTemplates that describe how a non-UI object should look like, when visual represented. DataTemplates are useful for representing standard CLR objects which are not UI controls. For example I could have a DataTemplate for a Person class that shows the name in a TextBlock and a picture of the Person in an Image.

<DataTemplate TargetType={x:Type model:Person}>

<StackPanel Orientation=Horizontal>

<Image Source={Binding Picture}/>

<TextBlock Text={Binding Name}/>




Note that I am using the data-binding syntax for binding to the Picture and Name properties of the Person class.

Similar to the DataTemplates are ItemTemplates, which are used in the context of a list control like ListBox, Tree, etc. ItemTemplates describe how each item in a list should appear.


Styles, themes for custom controls

    Styles are higher level constructs for describing additional properties of a control in addition to the Template property. Say I have five buttons on my form and I want all of them to be of a particular width (50px). I could do that in a <Style/> tag as follows:

<Style TargetType={x:Type Button}>

<Setter Property=WidthValue=50/>



Note how I target the Button control using the TargetType attribute. However the above style applies to all Buttons on the form. If you like only specific Buttons to take this style, you can qualify the <Style/> with a x:Key attribute.

<Style x:Key=WidthFiftyStyle TargetType={x:Type Button}>

<Setter Property=WidthValue=50/>



The Button can refer this style with the Style attribute. The {StaticResource WidthFiftyStyle} syntax is called a MarkupExtension and is used to reference resources.

<Button Style={StaticResource WidthFiftyStyle}>Submit</Button>


The standard controls that are available out of the box are useful for most scenarios. However you do want the ability to create your own custom controls. WPF provides you that ability and also gives you a chance to define a default style for your control. Since your custom control will be in a separate .Net assembly, the default style is specified in a generic.xaml file that sits in the /themes folder. When WPF loads your control, it probes into the /themes/generic.xaml file and looks for a style definition for that control (TargetType = your control’s type).


Databinding with property change notifications

    Data binding is a great way to do away with a lot of code to keep the UI consistent with the model. Bindings keep your logic clear and easier to maintain. However you do have to take some extra steps and enable your models to participate. In WPF a common way of doing this is to use a ViewModel that wraps the actual Model and also implement the INotifyPropertyChanged interface. The reason we use a wrapper around Model is because we don’t want to pollute the Model class with UI related information.

Inside your ViewModel you have to fire change notifications whenever a property changes, using the PropertyChanged event. This informs WPF that it has to update the corresponding UI element. INotifyPropertyChanged is good for a singular model class. If you have a ListBox control bound to a model-collection, then you need a ViewModel wrapper that extends the ObservableCollection<Model> class. The <> syntax indicates that it is a Generic collection (similar to the C++ templates) for the type: Model. With these extra steps you would have data-bound UI controls that automatically update whenever the model changes.

Custom events – RoutedEvents, Commands

    Most UI paradigms have a mechanism of propagating events raised on controls. Typically these events bubble-up from the child to parent. However WPF makes this propagation strategy customizable with RoutedEvents. All events in WPF are instances of RoutedEvents, which can either follow the Bubbling (bottom-up), Tunneling (top-down) or Direct (only on the element) strategy. Custom UI controls can define their own RoutedEvents.

In addition to RoutedEvents WPF provides a higher level abstraction of Commands. Commands are way of mapping user gestures to actions. The astute reader would have recognized that this nothing but the Command design pattern.


    UI assets like <Style/>, Templates, images, videos etc. are all specified in a ResourceDicionary with a key attribute. In other words, ResourceDictionary is a logical collection of all assets in your application. You can also nest ResourceDictionaries creating a more hierarchical grouping. Typically in a large application you would dedicate a single ResourceDictionary for a particular type of asset. So you might keep all your <Style/>s in a dictionary and DataTemplates in another dictionary. Both of these will then be nested inside a top-level dictionary. The syntax looks something like this:



<ResourceDictionary Source=Styles.xaml/>

<ResourceDictionary Source=DataTemplates.xaml/>




Note how the nesting is done inside the MergedDictionaries tag.

Packaging into assemblies

    ResourceDictionary is a great way to group related resources together inside an application. However If you want to reuse these dictionaries across many applications, then you would need a higher level abstraction. In .Net you can package all your ResourceDictionaries into an assembly and then reference that assembly inside your application. Packaging your commonly used assets into assemblies will help you create an asset-library for your organization.



    This post has been rather long and touches upon the various building blocks of WPF that enable the content-style separation. You have seen how the appearance and behavior of a UI control can be separated using ControlTemplates. DataTemplates are useful for providing a visual representation for your Model classes. Styles can be used for describing common set of properties for your UI controls. ResourceDictionaries can be used to group assets together and an Assembly can be used to package ResourceDictionaries for reusing across applications.

Databinding is a powerful feature for keeping the UI controls in sync with the model. This is done via property-change notifications. RoutedEvents and Commands can be used to map user gestures to actual business actions.

In the second subpart of this post, we will look at how Flex approaches the problem of content-style separation.

Flex and WPF: A comparison – Part 1

In this series of articles I will try to do a head-to-head comparison of many of the features in Windows Presentation Foundation and the Flex platform. In many ways these platforms embody similar concepts, but are also different in their own unique ways. As a Developer/Designer it is important to have a good understanding of the available choices when developing solutions for your clients. When I say solutions, I refer to Frontend development, the presentation layer. Having this knowledge enables us to borrow good practices from either camp to solve problems. A good example I can think of is the Cairngorm architecture for Flex, which is also equally applicable to WPF.

Windows Presentation Foundation (WPF) is a great step forward for UI development on Windows. It is a much simplified programming model that incorporates good OO principles, Design Patterns and proven practices right out of the box. Plus it is powered by a rich .Net framework 3.0 API that makes it an obvious choice for any new application development on Windows. It has a consistent model for developing for both Desktop and Web applications. UI development on Windows has not been particularly easy until Window Forms arrived with the .Net framework. Although WinForms made it a lot easier to develop UIs it still wasn’t an easy task to provide a rich user experience. So it was left to Third parties to develop frameworks/libraries for doing things like animation, formatted text, custom layouts, 3D, etc. Though it was technically possible, each framework/library was different and suited only to particular scenarios. What the developer community really needed was a single, consistent and standardized technology for doing UI development. WPF was the answer.

A similar story exists for the Flash community. Flash was capable of delivering rich experience from the very early stages. It had the technology for mixing text, images, animations, videos and even 3D (although using third party products). Over the last couple of years, there was a shift to bring Form based development into Flash. I think it was in Flash MX 2004, when the Data components were introduced, thus making Form development easier. However it didn’t seem like a deeply integrated solution. For example it was not easy to mix custom animations with the data components. Here too the need was felt for creating a unified platform for developing rich experiences which integrated UI components with the rest of the Flash technology. Flex was the answer.

It is thus clear that the technology offerings from Microsoft and Adobe have moved towards unification of all the UI capabilities, available thus far only as separate components with no common theme. Additionally each platform also does a clear separation of the presentation from the data, similar to the CSS – HTML separation on the web. With this separation it is possible to have a more natural workflow between the Designers and the Developers, something that was difficult earlier. The toolset that these technologies provide take that into account and make it clear where these boundaries exist. Microsoft has an Expression family of products specifically targeted at this workflow. Similarly Adobe has their popular Creative Suite that incorporates this kind of workflow. With CS3, Adobe will make it even easier to seamlessly exchange assets between PhotoShop, Illustrator and Flash.

In the next post I’ll dive deeper into the specifics of each technology and how they are similar.