Using Multiple Properties Or The Entire Object In a Converter Class for Windows Phone and WinRT

Kind of a long wordy title, what does it really mean? When you are creating a custom converter for Windows Phone or WinRT, you create a class that inherits from IValueConverter and implement a Convert method. In that method you're given (among other things) the value that has been bound (bind-ed sounds too funky, sorry) to your element and optionally a converter parameter that you can use to help you decide what your Convert method should return. For example, your parameter could return "true", "backwards", "Blazers", or whatever you want. The main limitation as you may be noticing here is that you can only pass a single value back. So what happens when you need to look at multiple properties of the item that is being used in the data binding in order to decide what to pass back from Convert? 

Here's a simple example from something I was working on. I'm binding to an item that has an "IsMine" and "IsOpen" property. If the current item has "IsMine" equal to true, then I will return different values depending on whether IsOpen is true or false. This obviously is not possible if you are just passing a single string back as your converter parameter. The trick is to not assign a value to the binding; when you do that, the entire item is passed in as the "bind-ed" value. So assume you've written a custom Convert method called MyColorConverter. You want to use that for the background color of a Border element, so you would configure the binding for it like this:

 

<BorderBackground="{Binding Converter={StaticResource DataItemsColorConverter}}">

 

Notice that usually you would say what field you are binding too like this: {Binding myField, Converter={blah}. By omitting a specific field for the binding value, you get access to the entire object. Then in my Convert method I can work with it like this:

 

    public class DataItemsColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {

            SharePointData.DataItem di = (SharePointData.DataItem)value;

 

            if (di.IsMine)
            {
                if (di.IsOpen)
                    return "#FF41719C";
                else
                    return "#FFED7D31";
            }
            else
                return "#FF7030A0";
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            //not going to be converting back
            return value;
        }
    }