Thursday, 18 April 2013

Different ways of adding converters in XAML

In this post I'd like to commit to memory several ways of adding converters into the xaml code. There's of course the built in:
Code Snippet
  1. <BooleanToVisibilityConverter x:Key="BoolToVisConverter"/>

As any other converter after that we can simply add it to binding configuration:
Code Snippet
  1. Converter={StaticResource BoolToVisConverter}}

There are other ways of adding and instantiating converters in code though. For instance, what, if we don't want to go through the hassle of adding a converter in resources every time we want to use one? Below you have an ordinary converter with additional property - which changes the converter into a singleton.

Code Snippet
  1. public class ThingToThingConverter : IValueConverter
  2. {
  3.     private static ThingToThingConverter _instance;
  4.     public static ThingToThingConverter Instance
  5.     {
  6.         get
  7.         {
  8.             return _instance ?? (_instance = new ThingToThingConverter());
  9.         }
  10.     }

Thanks to this, we can now use above converter without adding it first to window's/control's resources. Like this:
Code Snippet
  1. Converter={x:Static Converters:ThingToThingConverter.Instance}}">

Another way of doing this is by using MarkupExtension, it's similar to the above, but I find is slightly more comfortable:

Code Snippet
  1. public class SmthToSmthConverter : MarkupExtension, IValueConverter
  2. {
  3.     public static SmthToSmthConverter _converter = null;
  4.  
  5.     public SmthToSmthConverter()
  6.     {        
  7.     }
  8.  
  9.     public override object ProvideValue(IServiceProvider serviceProvider)
  10.     {
  11.         if (_converter == null)
  12.             _converter = new SmthToSmthConverter();
  13.         return _converter;
  14.     }

ProvideValue method is called whenever XAML processor examines a MarkupExtension node and returns our converter into the object graph. All this allows us to use the following markup:
Code Snippet
  1. Converter={Converters:ThingToThingEnumConverter}

No comments:

Post a Comment