Welcome to my fantastic blog, and very first blog post! In my first post I thought I would share my first experience with the .NET dynamic data type, while doing some Silverlight binding.
The scenario is I have a View, ViewModel and Model project. My Model project gets data from a WCF service, and sets the appropriate properties in the ViewModel. There's an ObservableCollection property in the ViewModel bound to a DataGrid in the View.
The data in the ObservableCollection can be filtered through a search within the application. I want a Label control to display the results of the search, such as "Your search returned 34 results". So I did something crazy! Binding the updated ObservableCollection to the Label. This could have been done with a separate property, being updated from the set of the ObservableCollection, but that approach was too boring.
So you may ask, how does a Label element bound to an ObservableCollection display text? Through the magic of binding converters...
XAML:
xmlns:conversion="clr-namespace:SampleBuddy"
<controls:ChildWindow.Resources>
<conversion:CollectionConverter x:Key="collectionConversion"></conversion:CollectionConverter>
</controls:ChildWindow.Resources>
<sdk:Label Content="{Binding WorkOrders, Converter={StaticResource collectionConversion}}" Foreground="Blue" Cursor="Hand"></sdk:Label>
WorkOrders is the ObservableCollection property from the ViewModel class, which implements INotifyPropertyChanged.
Converter Class:
namespace SampleBuddy
{
public class CollectionConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string text = "Your search returned ";
dynamic collection = value;
if (collection != null)
{
text += collection.Count.ToString() + " results";
}
return text;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{return value;}
}
}
To better learn how to implement the converter, check out this article.
So I was able to bind to an existing property, and update the display whenever the collection changes from the ViewModel. Since I couldn't cast the object, because it was referenced from the ViewModel and not the View, the dynamic data type came in very handy.
Hope you enjoyed my first post.
JK