Jerry Nixon @Work: Windows 8: 15 More Reasons why I choose XAML over HTML5

Jerry Nixon on Windows

Wednesday, June 20, 2012

Windows 8: 15 More Reasons why I choose XAML over HTML5

imageMetro developers building applications for Windows 8 have choices to make. A few weeks ago, I put together my top ten reasons I choose XAML. That really got me thinking. There are so many more than 10 good reasons why I prefer XAML. I thought I would continue the list.

First, let’s reflect on the first list:

  1. It’s a nail – I am a hammer
  2. Bind to anything
  3. Resolution independency
  4. Dependency properties
  5. Platform adoption
  1. OOP
  2. State
  3. Expression blend
  4. Debugging
  5. Vectors, vectors, vectors

I could have stopped there. Seriously, those 10 are enough. They are all really good reasons. Lots of developers commented on that blog to tell me that they could do some of those in JavaScript, too. My intention was not to prove that JavaScript was bad, my intention was to demonstrate why XAML is my choice technology. But, then again, most of those JavaScript comments were wrong (or stretching it).

Let’s not forget, XAML is one of 3 choices for Windows 8 Metro UI. You can leverage Direct3D for high-end games. Web-based games can leverage their investments with Metro’s native HTML support. And, then, there’s XAML.

And here we go…

11. Attached Properties

Dependency Properties made it in my first list. But I was remiss to not mention Attached Properties. Like Dependency Properties, they are property bags and can be bound and animated. But, unlike Dependency Properties, Attached Properties can be “attached” to controls (any control) without the control’s knowledge.

Attached Properties let developers extend control behavior or store information. Canvas.* and Grid.* are familiar attached properties. Literally, they extend controls to meet the developer’s needs, easily.

Hint: there is a built-in Visual Studio C# snippet (propa) that creates the basic structure of an attached property for you.

imageMSDN: One scenario that calls for the creation of an attached property is to enable an object to specify a unique value for a property that is defined in a different class object model. The defining class can read this value at run time after the various objects are created in relationships in an object tree.

Remember the pain

Native and third party controls deliver 99% of what your applications needs. With attached properties you extend behaviors without work-arounds or non-standard implementations. Problem solved.

12. Control Templates

Control templates remind me of OuterHtml but without losing the functionality of the element. XAML developers, using Control Templates, turn controls (visually) into anything without losing its underlying behaviors. It’s like a Transformer (the good kind!).

As a result, we see scroll bars looking like candles, radio buttons like chilies, and textboxes like televisions. Textboxes can be Images, Grids can be Radio Buttons, whatever you need! The real advantage is when you want to “tweak” a control by inheriting its template and adding some extra something your application needs. If you can dream it, XAML can do it.

imageMSDN: In the XAML framework for Metro style apps, you create a control template when you want to customize a control's visual structure and visual behavior. Controls have many properties, such as Background, Foreground, and FontFamily, that you can set to specify different aspects of the control's appearance. But the changes that you can make by setting these properties are limited. You can use the ControlTemplate class to create a template that provides additional customization. Here we show you how to create a ControlTemplate to customize the appearance of a CheckBox control.

Remember the pain

Native and third party controls provide significant benefit to your project but do not match the overall look and feel. With control templates, you can “skin” controls to fit your model. Problem solved.

13. Data Template Selectors

Data templates are fundamentally your ability to show data. If you are repeating data in some type of items control or individually in a content control, it’s the data template that defines how the data appears. Just set it or select it.

imageMSDN: You can place a DataTemplate as the direct child of an ItemTemplate property element in XAML. You can also define a DataTemplate as a resource and then reference the resource as the value of the ItemTemplate property. The XAML usage that defines the content for creating a data template is not exposed as a settable property. It is special behavior built into the XAML processing of a DataTemplate object element.

Even cooler? Let’s say you have a list of mixed data types – like dogs, cats, and birds. You may have a data template for each. It’s the data template selector that allows you to use ANY logic you want to determine which data template is used for a record. Go selectors!

imageMSDN: The base DataTemplateSelector class is not used as an object element in XAML. However, it is a common scenario to derive a custom DataTemplateSelector, map a xmlns prefix for the custom class and its namespace/assembly, and then refer to an instance of the custom class as defined in a Resources block in XAML. This makes it possible to refer to the custom template selector class by x:Key, and use that reference to set the value of properties such as ItemTemplateSelector in XAML templates and particular visual states.

Remember the pain

You show the same data in multiple places in your application. Because data templates can be a shared resource, you don’t have to repeat yourself. Some lists contain a mixture of item types, using data template selectors you can swap the data template before it is applied. Problem solved.

14. Linq & Lambda

To understand Linq & Lambda is to understand what makes them different. Regardless, they have been part of the .Net family since Framework 3.5 (Visual Studio 2008). Although there is a learning curve, developers who use them swear by them for enumerable operations like sorting, filtering, and so much more. There are technical reasons why they improve on traditional techniques. Linq (Language integrated query) has exposed databases, XAML, objects, even custom sources like Twitter to .Net developers with super-easy interoperability.

imageMSDN: LINQ introduces standard, easily-learned patterns for querying and updating data, and the technology can be extended to support potentially any kind of data store. Visual Studio 2008 includes LINQ provider assemblies that enable the use of LINQ with .NET Framework collections, SQL Server databases, ADO.NET Datasets, and XML documents.

Lambda expressions are anonymous methods that build expression trees to accomplish some task. I think Lambdas are *the* sufficient reason for picking XAML, period. What I mean is, the productivity gains, the reduction code, they are all amazing. I could stop here. But I won’t.

imageMSDN: When you use method-based syntax to call the Where method in the Enumerable class (as you do in LINQ to Objects and LINQ to XML) the parameter is a delegate type System.Func<T, TResult>. A lambda expression is the most convenient way to create that delegate. When you call the same method in, for example, the System.Linq.Queryable class (as you do in LINQ to SQL) then the parameter type is an System.Linq.Expressions.Expression<Func> where Func is any Func delegates with up to sixteen input parameters. Again, a lambda expression is just a very concise way to construct that expression tree. The lambdas allow the Where calls to look similar although in fact the type of object created from the lambda is different.

Remember the pain

Working with collections is a common task. You frequenly have to filter, bubble sort, and distinct your lists. The work isn’t hard but the code is long and confusing to maintain. With Linq and Lambda the same solutions are just a few characters. Maintenance is easier. problem solved.

15. It’s not standards-based

Anyone noticed the return of browser wars? It frustrates developers and is expensive for companies. Why? Because browser subtleties are not ironed out, they are positioned as differentiators. And so it goes.

This will never end you know. The HTML5 peace & harmony dream is a little naïve and a little stupid. Why? Because everyone wants to make their mark. Everyone wants to make their buck. And everyone sees themselves in a crusader.

The disadvantage to HTML is specification; as noble and as comprehensive as it may be, it will always be incomplete, always in dispite, and always speculative. The tides of opinion may prefer one implementation over another, but it will never matter. Non-standard is the desity of standards.

XAML, on the other hand, is less like democracy and more a dictatorship. The analogy is bitter but the reality is sweet. There is always a consensus, and it is what it is. It’s like comfort food. There is never wiggle room. Implementation is consistent across platforms.  Period.

Reality check: WPF is ten years old, Metro isn’t out of beta yet. The breadth & depth of WPF is a decade greater than Windows 8 Metro XAML (codename Jupiter). Some WPF features haven’t made it to Silverlight, let alone Metro –  features are certainly not in parity. But my point is not features – features will come, my point is implementation. As far as pixel placement, color depth, padding, borders, whatever – XAML is XAML is XAML and God bless America!

Remember the pain

Writing HTML and JavaScript that worked the same on all systems and all browsers meant a lot of extra development and, eventually, the lowest common denominator. Your lines of code exploded. XAML applications are all the same and always look the same. Problem solved.

16. Model view view model (MVVM)

One of the most popular and easy to use design patterns is Model View View Model (MVVM). Believe it or not, MVVM is from XAML! True. Check out this article snippet:

MSDN Mag: In 2005, John Gossman, currently one of the WPF and Silverlight Architects at Microsoft, unveiled the Model-View-ViewModel (MVVM) pattern on his blog. MVVM is identical to Fowler's Presentation Model, in that both patterns feature an abstraction of a View, which contains a View's state and behavior. Fowler introduced Presentation Model as a means of creating a UI platform-independent abstraction of a View, whereas Gossman introduced MVVM as a standardized way to leverage core features of WPF to simplify the creation of user interfaces. In that sense, I consider MVVM to be a specialization of the more general PM pattern, tailor-made for the WPF and Silverlight platforms.

It’s easy to love MVVM. It’s appeal explains its popularularity. It’s abstraction and separation of duties is clean and simple. And, it goes with XAML like peanut butter and jelly.

Remember the pain

Adding data to your application used to mean adding complexity. But MVVM is a consistent, simple approach. Now there’s similarity across projects and development teams. Problem solved.

17. Intellectual Property

Intellectual property is a legal term, right? We’re all grown ups here. We know there is no software silver bullet to hide code or logic from prying eyes. Tempt the tech community and it’s game over. We can make it difficult, but that’s it. Let’s not pretend.

So, this is a real problem. You or your company is paying real money to build a real product. Your solution, your approach, your code – it’s all property and it’s all worthwhile and worth money.

If you take your keys with you when you into the mall. If you lock your house when you go on vacation. Any of those, then you understand the value of risk and value. You’ve spent the money and time. Why give it away?

Having said that, we want to make it freaking difficult. 99% of all the IP snoops will stop at the first (maybe second) gate they hit. .Net developers have enjoyed dotfuscator for a long time. It makes .Net code run faster,sure, but also nearly impossible to reflect (reverse-engineer).

Boom. JavaScript has a similar obfuscator, but really is just a minify engine. Minify. That helps. Good for JavaScript, but .Net obfuscation is significant, improves performance, provides error reporting, and so much more. Give me a choice. I choose .Ne obfuscation to protect my software investment.

Techniques to protect IP (oh yeah, these are built in to the obfuscators!) – and makes it obvious why JS minify is more like a toy than real Intellectual Property protection: Symbol renaming, Overload renaming, String encryption, Tamper detection, Flow obfuscation, ILDASM suppression, Reflection suppression, Decompile suppression, Resource encryption, and Assembly encryption.

Remember the pain

Your code is worth time and money and you didn’t spend it to teach everyone else your magic. Using obfuscation, your intellectual property is protected. Problem solved.

18. Service Proxy Generation

When I call a cloud service, data is returned to me. Sometimes it is a string I parse myself, deserializing XML or JSON. I love to use Json2Sharp to save time (check it out!).

The process is easy and fast.  But the bulk of well-designed line-of-business services are SOAP, not REST. For a WSDL-defined service, adding a reference in Visual Studio automatically builds the proxies for to interoperate and leverage client-side, typed classes.

Unless you are paid by the hour (or the line), you will love the code generation in Visual Studio. (called T4 templates). Now, the interoperability is something you can assume. Best of all, updates or changes to service signatures is as simple as a right-click “Update Service Reference”.

imageMSDN: A WCF client consists of a proxy that enables an application to communicate with a WCF service, and an endpoint that matches an endpoint defined for the service. The proxy is generated on the client side in the app.config file and includes information about the types and methods that are exposed by the service. For services that expose multiple endpoints, the client can select the one that best fits its needs, for example, to communicate over HTTP and use Windows Authentication.

Remember the pain

Manually accessing services meant your application was brittle and needlessly complex. Using Visual Studio service proxy generation creates your code for robust interaction. Problem sovled.

19. The Desktop

If you are building a skill, why not unlock every Microsoft platform? XAML does that. Best of all, learning XAML gives you both the ability to write awesome, touch-ready Metro apps, windows phone apps, and web apps.

But, also use XAML for Windows 8 desktop applications (in WPF); reuse your C# in services, leverage it in web sites. XAML makes the most of your skills – even unlocking the desktop for custom LOB applications.

Remember the pain

Adobe Air and tech like HTML are cool but limit you too much. With the .Net framework and XAML you have the skills to build on every Microsoft platform. Problem solved.

20. A Culture of Design

WPF enabled it, Silverlight made it real, and it continues today through Metro. Any app, in any tech, must meet the needs of users, the business, and efficiency. That’s custom software’s definition of success. The latter, however, is best handled through User Experience and design.

XAML, more than most, intentionally targets designers to get involved early and often. Its separation of UI and implementation is a huge first step. But, Blend seals the deal. Blend delivers designers tooling  designers specific to UI layout and interactions.

MSDN: Depending on your own role in the development process, you might not interact with XAML much. The degree to which you do interact with XAML files also depends on which development environment you are using, whether you use interactive design environment features such as toolboxes and property editors, and the scope and purpose of your Metro style app. Nevertheless, it is likely that during development of the app, you will be editing a XAML file at the element level using a text or XML editor. Using this info, you can confidently edit XAML in a text or XML representation and maintain the validity of that XAML file's declarations and purpose when it is consumed by tools, markup compile operations, or the run-time phase of your Metro style app.

And here’s my point. Now that we (Microsoft) have extended Blend to serve HTML developers, too, everyone benefits. I won’t attempt to equate the functionality of Blend for HTML to Blend for XAML, but who’s counting? XAML, however, is steeped in a culture of design. It is the go-to UI for anything cool (think Silverlight & Surface) that Microsoft creates.

Reality check: many software projects don’t benefit from a budget that affords a designer. Or, many projects don’t benefit from a manager who values design. XAML’s culture of design is a self-fulfilling prophesy, a kind of positive peer pressure. Because XAML focuses on UX, XAML projects often reflect this predilection – even without a formal designer. It’s not ideal, but it’s better. Really better.

Remember the pain

Most apps are ugly. Just admit it. And your’s might be part of the problem. XAML enables better design, but also fosters it. Slowly we are seeing better UX. Problem solved.

21. Separation of Concerns

In software engineering separation of concerns has a few different meanings: To some it means scope creep. To others it means maintenance nightmare. To others it means job security. But, to a few, it means encapsulation, components, and testability.

Wiki: In computer science, separation of concerns (SoC) is the process of separating a computer program into distinct features that overlap in functionality as little as possible.

Look, your mother’s cookies are not the reason your are fat. But, they are an enabler that makes it possible. XAML is not the reason for separation of concerns, other technologies allow the same principles with distinct implementations, but the fundamental structure of XAML enables it, too. And when you end up knee deep in SoC, you end up liking it.

Listen, I am not talking about the shallow separation of HTML, CSS, and JavaScript. I am talking about symbolic separation in software. This is Aspect-oriented programming; it partitions code based on duty, vertical domain, or use case. One is a black box of function, one is a black box of activity.

Your architect can choose one over the other based on the latest magazine cover. ;) Either way, both are important – and show up frequently and rightly in larger projects. And, of course, both are equally enabled by XAML and the underlying OOP code.

Soap box: I am *not* talking about reuse here. Budgets are frequently subjected to developers chasing reusability. But developers rarely accomplish it, fellow developers rarely know about reusable components, and calcification sets in fast – reducing reusability to an expensive pipe dream. Yes, work to eliminate redundant code when possible; but, please, don’t target endless reuse. Just complete your task card and deliver a working product. Be proud of completion, not complexity.  </speech>

Remember the pain

Repeating yourself in software is sometimes okay, but typically just introduces needless maintenance costs. With Seperation of Concerns you get less redundancy. Problem solved.

22. Inline Invocation

XAML isn’t really markup, you know. XAML is a declarative UI referencing CLR objects, not page content, text, or layout. For example, placing a <GridView/> in XAML really is invoking the GridView control. The control then manipulates presentation. Built-in or custom, XAML references controls. This is what makes XAML powerful, but it is also why XAML provides inline invocation.

Consider these classes:


Such a structure is common to create a containers with data. When PEOPLE is invoked, data is generated by its constructor. Since we can invoke classes directly in XAML, our PEOPLE constructor runs before we ever debug the app! This gives us real data that really binds in our design surface – executing transitions, bindings, and repeaters inside Visual Studio.

Here’s how we do it:


In the code above, we are invoking a new instance of People. That instance is placed in the DataContext property of the Page. But we leverage the “d:” prefix which indicates XAML intended only for design time. As a result of this approach we have design time data that we know wont pollute our runtime experience. (This is an excellent way to implement MVVM with Design-time data)

But XAML also allows us to set properties after our invocation. Imagine the same scenario but without a constructor that creates sample data. We can, instead, create the sample data we need in our XAML directly. This helps us manage the data to suit our Page’s use case.

Like this:


In the code above, just like before, we are invoking the People list. But in addition, we are invoking our own Person members of the collection. With every invocation we have the ability to specify property values and use the resulting instances as our design time data context. I love it. You will, too.

Remember the pain

Design time data let’s you manipulate our UI with a real context. Otherwise, you have to run everytime you want to see a chance. With inline invocation design data is a snap. Problem solved.

23. Drawing Objects

Path illustrationNo need for canvas. No need for SVG containers. Just stinkin’ draw - anywhere. That’s right, and the drawing capabilities in XAML are (and have been) flexible and vector-based.

MSDN: The Path class enables you to draw curves and complex shapes. These curves and shapes are described using Geometry objects. To use a Path, you create a Geometry and use it to set the Path object's Data property.


In the code above, you can see the value of a design tool like Blend, no? I know Data could do it, but some of us need tooling. Nonetheless, the data attribute contains the definition for the arc. The rest are styling properties you use to make it look just so.

Line, Ellipse, and Rectangle are all wrappers for the Path element – so common shapes can be easily integrated by XAML developers. XAML can draw any 2/3d shape and leverage any transform to give the perspective or movement (which can leverage animation) you want.

MSDN: Because they derive from UIElement, shape objects can be used inside panels and most controls. The Canvas panel is a particularly good choice for creating complex drawings because it supports absolute positioning of its child objects.

Remember the pain

Not everything in your UI is going to be a rectangle. When you need a custom shape, there’s no need for third party libraries. Complex drawing is part of XAML. Problem solved.

24. Event and Data Triggers

XAML has the Routed Event. Consider this: a Routed Event can raise an event like a button’s click event, but it can also travel upward through the XAML visual tree (called bubbling). This allows containers to register for their children’s events.

MSDN: A routed event is a CLR event that is backed by an instance of the RoutedEvent class and registered with the WPF event system. The RoutedEvent instance obtained from registration is typically retained as a public static readonly field member of the class that registers and thus "owns" the routed event.

Here’s how Triggers look:


But even better than Routed Events are Routed Event Triggers. On XAML controls, developers leverage Routed Event Triggers to listen and react to Routed Events. Routed Event Triggers can then start or restart waiting storyboards. In this way, developers can declare a response to user action(s) without code behind. The execution engine builds the implementation.

MSDN: EventTrigger s apply a set of actions when the specified routed event occurs. For example, you may want to use EventTriggers to start a set of animations when the mouse pointer is over a certain user interface (UI) control.

Remember the pain

Interacting with the user is important but not always worth an additional code base. Using Event Triggers, your XAML can declare storyboard interactions directly. Problem solved.

25. Cascading Styles

XAML’s “cascading styles” are so much more than simple CSS classes. Remember in #22 where we discussed how XAML elements actually invoke CLR objects? <Style> is the same. And just like inheritance in Object Oriented Programming is a goliath benefit, Style inheritance is the ultimate!

Aside: I talked bout BasedOn in a previous article

Consider this:


In the code above, I am creating two TextBox styles – each of the two (good/green and bad/red) inherit from the base. This allows me to maintain the complexity within the base, then adjustment it in the concrete styles that are based on it.

Unlike CSS, I do not use multiple or nested styles or classes (confusing developers with an invisible priority tree), just the style I want. And every style can have a base or lineage of bases that create rich, themed and skinned interfaces that I can control programatically.

MSDN: There are several ways that styles in WPF can be extended or inherited. Styles can be based on other styles through this property. When you use this property, the new style will inherit the values of the original style that are not explicitly redefined in the new style.

Remember the pain

Themes, skins, and styles are important to create a rich application but can make things complex and confusing. With style inheritence, we control the style tree intuitively. Problem solved.


I could go on and on and on…

XAML is not better than HTML. For those of you chomping at the bit for me to say otherwise, look elsewhere. But, I can tell you this – and it harkens back to the number one reason I choose XAML over HTML – to me XAML is a nail, and I am a hammer. I have spent my career learning and mastering XAML. When the choice is mine, I choose what I know. That’s where I am most productive.

Reality check: I have been using XAML since 2009, not my whole career. I keep saying that. And, I keep saying “mastering XAML” which just makes my skin crawl. I know XAML pretty well, that’s all. You probably know more.

Having said that, a list like this helps demonstrate my choice is not stupid. It is based on real advantage that may or may not exist in other technologies. XAML is Microsoft’s go-to UI technology (Desktop, Metro, Windows Phone, Embedded, Xbox) and it has a long and bright future. Besides that, though, it’s also awesome, powerful, extensible, flexible, and stinking cool.

Some XAML books that may help

Also: Programming Windows, 6th Edition, by Charles Petzold – the only book I bought.

So, tell me: do you like XAML?

Seriously, I want to know.