The Binding Markup Extension

Last week I wrote a post about Markup Extensions with the intention of providing some background information for the Binding Class. If you’re doing an WPF or Silverlight development the Binding class is very important to know about. Further more, as a developer working side by side with a designer most of the work of integrating the design and the code is done through data binding.

The Basics

The Binding class is a very common type of markup extension. Its purpose is to update elements in your UI with values defined at other locations. Most of the time these other data sources will be ViewModels you create but it is also possible to bind to other UI elements.

So, for example, suppose you have a Customer object with a Name property and you want to display that in a text box. The Xaml to do this would look like this:

<TextBox Text="{Binding Name}" />

Pretty simple. The Binding markup extension accepts a Path as its default parameter. If you wanted you could optionally specify the full parameter name as well.

<TextBox Text="{Binding Path=Name}" />

These two snippets are effectively the same.

The Binding extension uses reflection based on the string you specify for the path to drill down into your object. So optionally you could choose to display the length instead of the actual string of the name, for example.

<TextBox Text="{Binding Path=Name.Length}" />

Additionally you can access indexed values through the path with this syntax:

<TextBox Text="{Binding Path=Name[0]}" />

Which would give you the first character of the string instead of the full name. These last two snippets are actually more tricky than this though. Since a string is immutable the character indexer and Length properties are read-only and Binding expressions do not like to bind against read-only properties. In this case we would need to either switch our Mode to be OneWay or OneTime.

Modes

<TextBox Text="{Binding Path=Name[0], Mode=OneTime}" />

This will result in a TextBox loaded with the string representation of the length of the name it is bound to but editing the text box will not actually do anything other than change the text in the text box. There are 5 modes to be aware of.

  • TwoWay
  • OneWay
  • OneTime
  • OneWayToSource
  • Default

Most of these are pretty straight forward but, surprisingly, Default can actually be tricky. Different controls may have different modes as default so if your binding doesn’t seem to be setting a value in the direction you’re expecting try a different mode.

UpdateSourceTrigger

This is the name of another important property. It is an enum value indicating when your binding should update the source (your ViewMode, a Customer in this case). So if we are bound to the Name property of Customer then whenever we type in the TextBox, by default, the name will only be updated when the TextBox loses focus. That is because for the Text property of a TextBox the UpdateSourceTrigger is set to LostFocus. If we want real time updating we could writing our binding like this:

<TextBlock Text="{Binding Name}" />
<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" />

Now as we type in the TextBox the TextBlock will be immediately updated. There are 4 possible values for UpdateSourceTrigger.

  • Default
  • PropertyChanged
  • LostFocus
  • Explicit

The default behaves similarly to the Mode in that different properties for different controls might have a different value for default. You should note that these usually only matter for OneWay or TwoWay bindings and its also dependent upon your ViewModel being implemented correctly (i.e. it implements the INotifyPropertyChanged interface). I’ll discuss view models more in another post however.

Source

Another important property is the Source property. In this example so far I haven’t specified the Source therefore I have been using the default source. By default the source is the value of the controls DataContext property. So that means to get the snippets above to work I had to set the DataContext property to a Customer object. It is also useful to know that if a Controls DataContext is null then it will use its parents DataContext and so on. So for my example I set the root windows DataContext to a customer object which allowed me to use the above Binding syntax.

public MainWindow()
{
    this.InitializeComponent();
    this.DataContext = new Customer { Name = "Justin Chase" };
}

This is a very simplistic way to do this but it works. Additionally you could specify your Source using the Source property. Typically you would do this by pointing it to a resource defined in your resources.

<Window.Resources>
        <local:Customer x:Key="customer" Name="Justin Chase" />
    </Window.Resources>
    
    <Border HorizontalAlignment="Center" VerticalAlignment="Center">
        <StackPanel>
            <TextBlock 
                Text="{Binding Name, 
                Source={StaticResource customer}}" />
            <TextBox 
                Text="{Binding Name, 
                UpdateSourceTrigger=PropertyChanged, 
                Source={StaticResource customer}}" />
        </StackPanel>
    </Border>

This is effectively the same except I now have no code-behind. As a more robust solution to this problem in WPF you can use the ObjectDataSource which gives you capabilities to construct objects in Xaml with constructor parameters or through factory methods. There are still quirks but it’s worth looking into.

Alternately I could have set a parent controls DataContext with a Binding instead of setting the Source on every child Binding like this.

<Window.Resources>
    <local:Customer x:Key="customer" Name="Justin Chase" />
</Window.Resources>

<Border HorizontalAlignment="Center" VerticalAlignment="Center">
    <StackPanel DataContext="{Binding Source={StaticResource customer}}">
        <TextBlock 
            Text="{Binding Name}" />
        <TextBox 
            Text="{Binding Name, 
            UpdateSourceTrigger=PropertyChanged}" />
    </StackPanel>
</Border>

It’s especially important to understand the Source property when you find yourself creating DataTemplates, because typically your DataContext is set from an unknown source and you will not be able to set the Source.

Converter and ConverterParameter

The Converter is a wonderful thing and is very simply to understand. The key to a good converter is the IValueConverter interface. Simply implement this and add your class to your Resources and you’re ready to convert! The converter simply converts a value to and fro as it passes through the Binding. I will write more details on this in another post.

The framework comes with a number of Converters but the only one I’ve ever found to be of any use is the System.Windows.Controls.BooleanToVisibilityConverter. But you will no doubt find the need to create many for yourself.

One cautionary note with converters, Converters are powerful but they can also be used to mask architectural problems with ViewModels. If you find yourself using a Converter for anything more than just changing something into a string and back you should probably take a step back and rethink things. I’m not saying you definitely have a problem but it’s worth thinking twice about. I will write in more detail about how to properly construct ViewModels in another post.

ElementName and RelativeSource

The element name is an alternative to the Source property. You either specify the ElementName or the Source but not both. If you specify the ElementName then you’re saying that you want to bind against the value of another control in your UI. The Path is essentially the same except you’re binding against a Control instead of a ViewModel. If you have a control that has a name specified with the x:Name attached property then that is the value you will want to put into the ElementName property.

<TextBlock 
    Text="{Binding Text,
    ElementName=tb}" />
<TextBox 
    x:Name="tb"
    Text="{Binding Name, 
    UpdateSourceTrigger=PropertyChanged}" />

Additionally you can set the RelativeSource property if you need to get to controls in a totally different branch of the control hierarchy or different properties of yourself. The value passed into the RelativeSource property is an Markup Extension, aptly named, RelativeSource. To acheive the same thing as above except using the RelativeSource property you could do this:

<StackPanel DataContext="{Binding Source={StaticResource customer}}">
    <TextBlock 
        Text="{Binding Children[1].Text,
        RelativeSource={RelativeSource 
            Mode=FindAncestor, 
            AncestorType={x:Type StackPanel}}}" />
    <TextBox
        Text="{Binding Name, 
        UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>

ValidationRules

I was struggling with what to write about in this section. I’ve decided to just be honest. My work with CSLA has caused me to come to the conclusion that the validation rules mechanism in WPF / Silverlight Binding expressions is simply inadequate. So basically what I’m saying to you is to simply not use it at all, it’s awful.

The main reason why I think you shouldn’t use it is because it’s completely predicated on the mechanism of throwing exceptions from within a property. Which is a pretty rude thing to due normally. Additionally it requires that you throw a specific WPF type of exception to trigger the validation failure rule… which tightly binds you to WPF. This is evil. And frankly, it’s easy to just write your own validation scheme that WPF / Silverlight is perfectly happy with. In CSLA we wrote a validation scheme that includes prioritization, dependency, asynchrony, severity and multiplicity. And it wasn’t even that hard…

So do yourself a favor and don’t even bother with the built-in validation mechanisms. Additionally, if I didn’t quite sell you with the rational approach, then be aware that the XAML required to write WPF style validation is so Flying Spaghetti Monster-awful that it makes me want to barf just looking at it.

StringFormat

This is a pretty cool little property that is relatively new to WPF that allows you to format the output of the bound text without having to actually write a custom converter. Essentially the string that goes into this property is the same string that you would put into a call to string.Format(…). The only difference is that if you want to put {0} at the beginning of the string you have to escape it with an extra {}… yeah I know. Its hideous but better than not having it… barely. Here is an example of the two usages:

<TextBlock 
    Text="{Binding Name.Length,
    StringFormat='Name Length: {0}'}" />
<TextBlock 
    Text="{Binding Name.Length, 
    StringFormat='{}{0:C}'}" />

IsAsync

Frankly… stay away from this one too. I’ve wanted to use this so many times but have always found the model to be overly simplistic. Asynchronous code is hard, there is no free pass and this just adds to the confusion. You might give it a try if you have some ultra simple scenario but don’t expect it to take you into a completely asynchronous UI.

Many others…

For a complete list of properties head to this site on MSDN http://msdn.microsoft.com/en-us/library/system.windows.data.binding_properties.aspx

Xaml Markup Extensions

Markup extensions for xaml are a lot of fun. There are a bunch of freebies that come with the framework but you can easily create your own as well. Here’s a brief list of common markup extensions that come with the framework:

  • Binding
  • TemplateBinding
  • StaticResource
  • DynamicResource

As a WPF developer you’ll probably run into these every day. Markup extensions are powerful and also very simple to master. If you’re not sure what I’m talking about here is a sample of what a markup extension looks like inside of Xaml:

<TextBlock Text="{Binding Name}" />

If we break it down there are only a few basic rules. The first section of the markup extension is the Type (as in .NET type) following that is a comma separated list of Properties and values. The first property name is optional, each markup extension may specify what the default property is and if a value appears first and without a property name it is assigned to that default property. So this means that the markup extension:

{Binding Name}

Is a class called “Binding” and has a default property, the value of which is “Name”. Also, it’s interesting to note that, like Attributes in C#, the “Extension” part of the type name is optional. If you create a markup extension called “TestExtension” you would reference it in Xaml as “{Test}”.

Also it is possible to use other markup extensions as values for properties. Therefore it’s possible to have a more complex markup extension such as:

{Test Name, Color={StaticResource color}}

For this markup extension there are two properties, one is default and is being assigned the value “Name” while the other is called Color and is being assigned a color from this controls resources.

To create your own markup extension you simply create a class than inherits from the abstract base class MarkupExtension. Here is an example of a custom markup extension for rotating images:

namespace WpfApplication1
{
    using System;
    using System.Windows.Markup;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;

    [MarkupExtensionReturnType(typeof(BitmapSource))]
    public sealed class RotateExtension : MarkupExtension
    {
        public RotateExtension() { }

        public RotateExtension(BitmapSource source)
        {
            this.Source = source;
        }

        public BitmapSource Source { get; set; }

        public double Angle { get; set; }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            IXamlTypeResolver resolver = (IXamlTypeResolver)serviceProvider
                .GetService(typeof(IXamlTypeResolver));
            IProvideValueTarget target = (IProvideValueTarget)serviceProvider
                .GetService(typeof(IProvideValueTarget));
            BitmapSource rotatedSource = null;
            if (this.Source != null)
            {
                RotateTransform rotation = new RotateTransform(this.Angle);
                rotatedSource = new TransformedBitmap(this.Source, rotation);
            }

            return rotatedSource;
        }
    }
}

Adding the MarkupExtensionReturnType attribute on the class is optional. You’ll need at least one public parameterless constructor and one optional constructor with your default parameter. Then just implement the ProvideValue method! The service provider contains (usually) at least the two services listed here. There is no guarantee they will be there but they are pretty much always there. My example applies a very simple RotateTransform to the bitmap before providing it. Here is the accompanying xaml.

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    x:Class="WpfApplication1.MainWindow"
    x:Name="Window"
    Title="MainWindow">
    <Border HorizontalAlignment="Center" VerticalAlignment="Center">
        <StackPanel Orientation="Horizontal">
            <Image Source="img15.png" Stretch="None" />
            <Image Source="{local:Rotate img15.png, Angle=90}" 
                   Stretch="None" />
        </StackPanel>
    </Border>
</Window>

Notice the need to add the namespace “local:” to my extension. This is sort of unfortunate but necessary. I would recommend creating fairly terse names for you extensions to help save you some typing. Also notice that I could just use “img15.png”, which is the path of a file added to my project as a resource instead of trying to create some type of a bitmap source object. The xaml deserializer will realize that the optional parameter on my constructor is a BitmapSource and it will try to use the TypeConverter associated with that type to convert it before giving it to me. Type converters will be the topic of another blog post however.

EDIT:

Sorry folks I had to disable comments on this post due to tons of spam coming in from somewhere. Also, somehow the image above here got overwritten by an image from another post so I deleted it.

Expression Blend for Developers

Expression Blend often times is portrayed as a tool for graphic designers, which is fair enough, but this can be a little daunting for people who are artistically challenged like myself. If you’re primarily a developer you probably want to use a developer tool, like Visual Studio, to do your work. But I might assert here that Expression Blend actually is a tool for developers and not to be dismissed! I often hear one of the following reasons from developers as to why they might avoid using Blend.

  • I’m not “artsy” I prefer to dig into code, none of this drag-and-drop business.
  • I’m working on a business application, making it look pretty is unnecessary, costly, fluff.
  • Having a dependency on .NET 3.5 isn’t worth it, I’ll stick with .NET 2.0.
  • etc.

I can summarize my response to all of these positions by simply saying that I would never choose to do WinForms or an MFC application over Wpf in any circumstances. If you’re not using Wpf, even for simple business applications, even if you don’t have a single artistic bone in your body you’re definitely missing out. I might even go one step further and saying you’re actually making a mistake.

I might even go so far as to say that the same thing holds true for doing Silverlight development over standard Web development. The benefits aren’t nearly as stacked in favor of Silverlight for the web as Wpf is for desktop applications but it’s still a winner in my eyes. Additionally, with Silverlight 3 you’ll be able to create applications that can be run as desktop applications or on the web. That kind of re-usability (of skills and code) is another win.

And Blend is the tool to make these technologies come alive.

User Experience

User experience is not “fluff” or unnecessary. Usability translates directly into money, even for simple business applications. The less usable your application is the larger the training costs, the longer the development time, the likelihood of data input errors becomes higher, and just general unhappiness from your customers can be a result if you don’t pay attention to UX. This is a competitive market, customers more and more have higher expectations from every piece of software they use, especially ones that they’re paying money for.

And believe it or not as a developer you’re definitely going to want to learn a little something about Expression Blend. You don’t need to be an expert and know all of the various tricks and commands but you’ll probably find a huge productivity gain from just from knowing a little. And as we know, productivity is money in your pocket.

Roles

Typically if you’re a developer in a Wpf project you’ll find yourself in one of two roles.

  • Designer supporter
  • The Devigner (Designoper?)

The Designer Supporter

As the developer tasked to work along side designers you may think that because you have people who are tasked with doing all of the UI work you don’t need to know anything about Xaml or Blend. Or even worse, you may know too little but just enough to screw up the workflow for the designers. Knowing a little bit about Expression Blend and how to effectively support your Designers will be critical to your success. Here is a quick list of things you should learn about.

  • DataBinding
    • Binding class
    • IValueConverter
    • ObjectDataProvider
    • Design time data
  • ViewModels
    • INotifyPropertyChanged
    • INotifyCollectionChanged
  • Markup Extensions
  • Behaviors
  • Custom Controls
    • Visual State Manager
    • DependencyObject
    • DependencyProperty
    • Attached properties
  • Theming
    • Generic.xaml
    • [assembly:ThemeInfo]
  • Commands
  • Routed Events

As a developer supporting designers you will find yourself either having to DataBind your ViewModels to an existing UI created by the designers or you will have to create ViewModels that the designers can then build their UI around. Most likely the designers will want the former while developers will want the latter. All I can say is that the sooner you bring them both together and make it real the better off you will be.

The above topics will be crucial to know in order to preserve the developer / designer workflow with minimal friction.

The Devigner

You may actually be artistically inclined enough to claim this title yourself but then again maybe you’re simply tasked with this out of necessity. For developers who find themselves plunging into the world of Expression Blend here is a list of tasks, in addition to the previous list, that you may want to start learning about.

  • Templates
    • ControlTemplate
    • DataTemplate
    • DataTrigger
    • TemplateBinding
  • Visual State Manager
  • Storyboards
  • Commands
  • Styles
    • Setters
    • Triggers
  • Resources
    • Merged Dictionaries
  • Gradients
  • Layout Controls
    • Grid
    • StackPanel
    • ListBox
    • DockPanel
    • Canvas
  • Layout Transform vs. Render Transform

And really the list goes on and on. There is a myriad of things to learn but this is a pretty good start.

The important thing to know here though is that Expression Blend is not just a tool for Designers. It’s simply a tool geared towards creating rich interactive applications. Designers and developers alike will benefit greatly from this tool in any Wpf project, whether you’re just hooking up DataBinding for designers or doing it all yourself.

I would like to break down each of these topics in following blog posts with a developer oriented slant and how they can be done in Blend, so keep an eye out for those!

MIX09 Announcements

There are lots of cool videos of demos and discussions over at Mix09 today. If you haven’t been there you should definitely head on over.

http://live.visitmix.com/

There are lots of cool announcements for new features for the next version of various Microsoft products. Too many for me to even enumerate in a single blog post actually but what’s really exciting is that I finally get to tell everyone what I have been working on these last couple on the job at Microsoft.

I have been working with a small team of developers, here in Minneapolis, who are responsible for the Photoshop Import feature of expression studio. It’s been a very interesting an exciting project so far and it seems like something that developers and designers are both very happy about. Here is a screen shot from the Mix demo site.

ExpressionBlend3PhotoshopImportFeature_web[1]

We’re able to read the layer information from a Photoshop file and import them as separate controls into Blend. Once there a developer can make those generated layers into real interactive controls like anything else in Blend. There is also a re-import feature to ease to workflow from designer to developer. This exact incarnation of the importer is available in the build of Blend 3 Preview, so download that and give it a shot! Feel free to send me feedback if you do try it out.

Expression Studio and MIX09

Tomorrow is Day 1 of MIX09, if you’re not aware of this then you must be living on mars should amble on over and check out what’s in store this year. There’s a lot I can’t tell you but I can say there are tons of cool new features being announced for the first time tomorrow, including the one that I have been working on here in Minneapolis. Also, there are some features that will be demoed during the keynote that will not be apart of the public CTP released at the same time so you should definitely check that out to get a complete idea of the sweetness of the real release.

If you have any questions about features feel free to ask me sometime tomorrow after the keynote 😉 Until then it’s all hush hush.