Thursday, 23 October 2014

ComboBox binding in Workflow activities

Today I was creating a simple activity with a couple of combo boxes, and came across a problem where the binding wasn’t working correctly (well, at all). I had an InArgument<string> property on my activity, and wanted to set this from a combo box on the design surface. I guess I haven’t done this before as it doesn’t work out of the box, and you need to write an IValueConverter to get it working. I’ve trodden this path before but this was a bit of a tricky beast.

After some wailing and gnashing I came up with the following base class converter…

public abstract class ComboBoxToModelItemConverter<T> : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
T retVal = default(T);

ModelItem mi = value as ModelItem;

if (null != mi)
{
var arg = mi.GetCurrentValue() as InArgument<T>;

if (null != arg)
{
var expression = arg.Expression;
var literal = expression as Literal<T>;

if (null != literal)
retVal = literal.Value;
}
}

return retVal;
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return new InArgument<T>((T)value);
}
}





I then created a concrete class to bind to InArgument<string>…

public class ComboBoxStringToModelItemConverter : ComboBoxToModelItemConverter<string>
{
}



With that created I could then get the binding to work by adding the converter to the binding. I have a class that contains TemplateId and Name, I wish to show the Name on screen but store the TemplateId (and this is mapped to an InArgument<string> on the activity). The XAML is as follows…

<local:ComboBoxStringToModelItemConverter x:Key="comboConverter"/>


<ComboBox ItemsSource="{Binding Templates}" 
SelectedValue="{Binding ModelItem.TemplateId, Converter={StaticResource comboConverter}}"
SelectedValuePath
="TemplateId" DisplayMemberPath="Name" />



With that done it all works as expected. I’m surprised that a converter such as this doesn’t exist in the Workflow libraries – and also in the many, many years I’ve been playing with Workflow that I’ve not needed one. Anyhow, I hope this is of use to someone!

2 comments:

Leadership and Organisational Excellence said...

Oh so you finally created the Base Class convertor in order to do the binding task in combo box.You have intelligently found out the way out.

best essays online said...

Wow looks pretty complex as well as amazing for a amateur like me, great post! Hope to see more of your work soon, you seem like a very talented programmer.