Recently I ran into a little challenge recently on a Silverlight 3 project using the SharePoint 2010 Client Object Model (ClientOM). I wanted to bind a collection of list items I was getting back from SharePoint to a list box. I wanted to have a way to easily use the elegant data binding syntax in Silverlight without having to write managed code… something I could reuse over and over in a few projects.
The challenge is that the data in a SharePoint list item as seasoned SharePoint developers know is in a named collection. For instance, if you want the DueDate field, you access it using the SPListItem["DueDate"].Tostring()
syntax (ListItem["DueDate"].ToString()
with the ClientOM). Unfortunately the binding syntax in Silverlight isn’t very friendly for this type of data.
Thankfully there is a capability in Silverlight (and WPF) that allows you to create converters. Basically a converter takes in an object, the thing being bound to the control, and returns back another object. Once this converter is registered, you can then reference it in your data binding syntax in XAML.
Custom Converter
The first thing I did was write the code for the converter and drop it in the project. As you can see from the code below, I first check to see if there is content passed in during data binding and also default the field to show as “Title”. This is done by checking a parameter that is passed into the method (more on this in the XAML data binding in a moment). I then check to see if the name contains the prefix of “Lookup.”. If so, I do some special stuff to get the value from a lookup field, otherwise I just grab the data and return it back as a string.
In order to use this converter, you need to register it in the XAML page you’re going to use it in. Since I use it in multiple places in this project I’m doing, I did this in the App.xaml file:
Data Binding XAML
With everything in place, I then write the pieces that fetched the data from SharePoint using the ClientOM and then bound it to the page’s DataContext property. Nothing fancy there… what I want to show you is the data binding syntax. When I data bound the ClientOM ListItem object I want to use my custom converter. I also want to pass in a parameter telling the converter which field to use.
In the following screenshot you can see how I’ve registered the converter for the Text property on both TextBox controls. Notice how one is using the Price field (which you’d get on the server like this: SPListItem["Price"]
) and a lookup field in the second (SPListItem["Category"]
).