Click here to Skip to main content
15,893,368 members
Articles / Web Development / HTML

MultiBinding in Silverlight 5

Rate me:
Please Sign up or sign in to vote.
4.97/5 (23 votes)
18 Nov 2011CPOL12 min read 136.4K   3.2K   33  
An enhanced MultiBinding markup extension implementation for Silverlight 5 with support for bindable Converter, ConverterParameter and StringFormat
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Text.RegularExpressions;

namespace SilverlightMarkupExtensions
{
    public class StringFormatMultiValueConverter : IMultiValueConverter 
    {
        public StringFormatMultiValueConverter()
        {

        }

        private static readonly Regex ArgRefRegex = new Regex(@"%(\d+)");

        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string format = parameter as String;
            string result;
            if (format != null)
            {
                format = ArgRefRegex.Replace(format, "{$1}");
                result = String.Format(culture, format, values);
            }
            else
            {
                result = String.Concat(values);
            }
            return result;
        }


        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            if (targetTypes.Length == 1) return new object[] { value };
            throw new NotSupportedException("ConvertBack is not supported by " + GetType().Name);
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Sweden Sweden
Henrik Jonsson is a Microsoft Professional Certified Windows Developer (MCPD) that currently works as an IT consultant in Västerås, Sweden.

Henrik has worked in several small and large software development projects in various roles such as architect, developer, CM and tester.

He regularly reads The Code Project articles to keep updated about .NET development and get new ideas. He has contributed with articles presenting some useful libraries for Undo/Redo, Dynamic Linq Sorting and a Silverlight 5 MultiBinding solution.

Comments and Discussions