Databinding to an enumeration in WinRT

This article demonstrates how to databind a radiobutton to an enumeration element, in a WinRT Metro application. The MVVM viewmodel has a property of an enumeration type, which is bound to the IsChecked property of some radiobuttons. A value converter compares the value from the viewmodel with an enumeration element that is provided as parameter to the converter. The Convert method returns true if both match, the ConvertBack method updates the bound value when the radiobutton is clicked or tapped.
 
Here's a screenshot of the attached sample application. The radiobuttons are bound to the CarColor property -an enumeration- of the viewmodel. The Vote-button updates that same property through a command:

The converter is much more complex than the WPF version from my previous article, it's even more complex than its corresponding Silverlight version that you can find here.

Here's a list of reasons why the implementation was not so straightforward:

  • The x:Static markup extension is not allowed in a Metro application,
  • Binding.DoNothing does not exist in WinRT, and
  • unlike in WPF or Silverlight, the converter receives the enumeration value as an integer instead of a string.

When I observed all of this, my first reaction was AARGH!!! Don't worry: it was not a call of anger and frustration. In the noble Antwerp language aerg just means 'this is bad'. Non-believers: just follow this link.

As a result, the converter is much more complex than expected. It reconstructs the enumeration parameter from the binding expression by string parsing and reflection. Here's how it looks like:

namespace U2UConsult.WinRT.Converters
{
    using System;
    using System.Globalization;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Data;

    /// <summary>
    /// Converts an enum to a boolean.
    /// </summary>
    public class EnumToBooleanConverter : IValueConverter
    {
        /// <summary>
        /// Compares the bound value with an enum param. Returns true when they match.
        /// </summary>
        public object Convert(object value, string typeName, object parameter, string language)
        {
            try
            {
                string parm = parameter.ToString();
                int lastDot = parm.LastIndexOf(".");
                string enumName = parm.Substring(0, lastDot);
                string enumValue = parm.Substring(lastDot + 1);

                Type t = Type.GetType(enumName);
                string s = Enum.GetName(t, value);
                object b = Enum.Parse(t, enumValue);
                return b.ToString() == s;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// Converts the boolean back into an enum.
        /// </summary>
        public object ConvertBack(object value, string typeName, object parameter, string language)
        {
            try
            {
                string parm = parameter.ToString();
                int lastDot = parm.LastIndexOf(".");
                string enumName = parm.Substring(0, lastDot);
                string enumValue = parm.Substring(lastDot + 1);

                Type t = Type.GetType(enumName);
                object b = Enum.Parse(t, enumValue);

                return b;
            }
            catch (Exception)
            {
                return DependencyProperty.UnsetValue;
            }
        }
    }
}

In your application, all you need to do is create an enumeration:

public enum CarColor
{
    Yellow,
    Red,
    Pink,
    Black
}

In the viewmodel, create a property of the enumeration type:

private CarColor carColor = CarColor.Black;

public event PropertyChangedEventHandler PropertyChanged;

public CarColor CarColor
{
    get { return carColor; }
    set {
        this.carColor = value;
        this.PropertyChanged.Raise(this, (o) => o.CarColor);
    }
}

The propertychanged notification makes sure that the radiobutton follows all modifications of the property.
 
In the view, define the converter instance as a resource in XAML:

<UserControl.Resources>
    <cv:EnumToBooleanConverter x:Key="EnumToBooleanConverter" />
</UserControl.Resources>

Bind the viewmodel's CarColor property to the Ischecked property of each radioButton. The enumeration value is provided as parameter to the converter with its fully qualified name. Also, you have to set the binding mode to TwoWay, and make sure that every radiobutton has its own GroupName. This is because we can't use Binding.DoNothing in the IValueConverter.ConvertBack Method. We always have to return the parameter, or DependencyProperty.UnsetValue. Both (re-)trigger all radiobuttons in the same group and that's not what we want; more info here.

Here's the full binding syntax in XAML:

<RadioButton Content="Giallo Modena"
                GroupName="Yellow"
                IsChecked="{Binding CarColor, Mode=TwoWay, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter=U2UConsult.WinRT.DataBindingToEnum.ViewModels.CarColor.Yellow}" />
<RadioButton Content="Rosso Corsa"
                GroupName="Red"
                IsChecked="{Binding CarColor, Mode=TwoWay, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter=U2UConsult.WinRT.DataBindingToEnum.ViewModels.CarColor.Red}" />
<RadioButton Content="Rosa Insapora"
                GroupName="Pink"
                IsChecked="{Binding CarColor, Mode=TwoWay, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter=U2UConsult.WinRT.DataBindingToEnum.ViewModels.CarColor.Pink}" />
<RadioButton Content="Matte Nero"
                GroupName="Black"
                IsChecked="{Binding CarColor, Mode=TwoWay, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter=U2UConsult.WinRT.DataBindingToEnum.ViewModels.CarColor.Black}" />

This solution is more error-prone and definitely slower than the WPF version, but it does the job. That's the good news. I also have bad news: the pink Ferrari photo is NOT photoshopped, aerg.

Anyway, here's the full source code. It was developed with Visual Studio 11 Developer Preview: U2UConsult.WinRT.DataBindingToEnum.zip (364,11 kb)

Enjoy!


Comments (4) -

January 10. 2012 09:33 PM

Silicone Sealants

Incredibly helpful appreciate it, There’s no doubt that your current followers might want considerably more content such as this keep up the great work.

Silicone Sealants

February 15. 2012 06:58 PM

guocijun

    A large number of guitar players like to end up <strong><a href='http://www.authentichervelegerdress.com/'; title='Herve Leger Outlet'>Herve Leger Outlet</a></strong> being a fabulous a lot better nylon string guitar gambler. Guitarist call for others really constantly as to why there're not likely inside the place they really want and additionally what can individuals implement. In the last I had Victor Cruz Jacket quizzed other people all the really quite similar topic. Fairly quickly Document began to be aware of all the information. Much like you've gotten more than likely executed, Concerning examine a large amount of methods to carry out nylon string <strong><a href='http://www.authentichervelegerdress.com/'; title='Herve Leger'>Herve Leger</a></strong> guitar selection interviews and additionally reports right from awesome guitarplayers. Document quite often located the software demoralizing at any time when the topic of learn do the job nylon string guitar went " up " or possibly the moment advice Victor Cruz Jacket was first produced relating to fixing they've getting involved in. By means of a good number exceptions, little time and additionally locale was first truly tenacious using this. This isn't bizarre to find out a fabulous nylon string guitar <strong><a href='http://www.authentichervelegerdress.com/'; title='Herve Leger Dress'>Herve Leger Dress</a></strong> gambler produce assist to know that you perform practicing the guitar summed " up " for no more than 3 sayings: Sign up! Go along with!! Workouts!!! Document consider pictures first of all was first getting to know a way to do the job nylon string guitar A totally free workouts relating to a lot of conditions for that reason fully extended all the draws to a close about great fingers might offer in the communication and additionally deterioration just for months. <strong><a href='www.officialnflpackersshop.com/.../'; title='Clay Matthews Jersey'>Clay Matthews Jersey</a></strong> Individuals realise that doing business closer to certainly is the essential active ingredient. Actually a fabulous little league gambler workouts a small number of times thereafter is ready to do the job as much human eye any NATIONAL FOOTBALL LEAGUE little league gambler? Hardly likely really are everyone abreast an issue around relating to how to do the job practicing the guitar afterward to make sure you only just put into practice. Into my time consuming vision to show right into an <strong><a href='www.officialnflpackersshop.com/.../'; title='Aaron Rodgers Jersey'>Aaron Rodgers Jersey</a></strong> awesome gambler Document carefully acquired take note of about the things performed and additionally the things will not - in which issues basic skills really are specific and additionally in which issues really are (at a minimum into my school of thought) are certainly not. I presume the subsequent 20 helpful hints experience proven include delightful successes to make sure you people use them: 1. Educate yourself! Aging subject the things old tier you will located at may well and additionally might <strong><a href='www.authenticgiantsshoponline.com/.../'; title='Justin Tuck Jersey'>Justin Tuck Jersey</a></strong> frequently figure out nylon string guitar alot more. Once you are in latest at a status www.superbowlgiantsjerseystore.com to recognize nylon string guitar via the web, grasping a fabulous apartment nylon string guitar explore technique, or possibly feature any pro for your needs to know a way to carry out nylon string guitar then your relating to the most suitable display. Might no one will come to be mission this approach (or possibly once you fully feel the today's apartment have a look <strong><a href='www.authenticgiantsshoponline.com/.../'; title='Ahmad Bradshaw Jersey'>Ahmad Bradshaw Jersey</a></strong> at tutorial is not actually aiding you sufficiently for arriving at any objective) Document fervently strongly recommend buying revolutionary 1. Constantly anxiety the correct ways really important it's truly to locate a brilliant family home have a look at tutorial you got it for your needs! Your premises have a look at tutorial (or possibly consultant) might repeatedly come to be Ambition Orientated. Any time the country's not likely locate one additional technique or possibly consultant to analyze by means of! Are <strong><a href='www.authenticgiantsshoponline.com/.../'; title='Hakeem Nicks Jersey'>Hakeem Nicks Jersey</a></strong> unable to amount of reliability place have a look at technique or possibly pro to make sure you quickly deliver statistics or possibly what to sign up - you're able to become all those points around the world, what you should will want is seen as a understand technique or possibly consultant so, who: A fabulous. Has found out the things any dreams really are. G. Loves you approximately aiding you grasp any dreams. Implement. Has found out how to help grasp <strong><a href='www.authenticgiantsshoponline.com/.../'; title='Jason Pierre-Paul Jersey'>Jason Pierre-Paul Jersey</a></strong> any prey. Every different of united states comes with a lot of all-natural efficiency about some kind. You'll already understand what your site is normally or possibly you are able to not likely still came across the software. Any time obtaining more suitable guitarist will not be upcoming simple and easy for your needs which usually plainly stands for you can be much like the sleep of united states.<br>

guocijun

February 21. 2012 07:07 PM

birthday wishes

It is really nice for me to see you and your great hard work again.Every piece of your work look excellent.Looking forward to learning more from you!
http://www.smsify.com/birthday-sms.html

birthday wishes

February 21. 2012 07:15 PM

web

Excellent post and wonderful blog, I really like this type of interesting articles keep it up.
www.newsflap.com/category/web/

web

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

Download the U2U brochure

Download Brochure

Receive the U2U Newsletter. Submit your email address:
 
 


 


Search

rss  RSS

Tags

Recent posts

None

Archive

Blogroll