More Adventures in MVVM In my last post, I outlined the powerful features that are available in the ViewModelSupport. It takes advantage of the dynamic features of C# 4.0 (as well as some 3.0 goodies) to help eliminate the plumbing that often comes with writing ViewModels. If you are interested in learning about the capabilities, please take a look at that post and look at the code on CodePlex. When I wrote about the ViewModel base class, I complained that the features did not work in Silverlight because as of 4.0, it does not support binding to dynamic properties. Although I still think this is a bummer, I am happy to say that I have come up with a workaround. In the Silverlight version of my base class, I include a PropertyCollectionConverter that lets you bind to dynamic properties in the ViewModelBase, especially the convention-based commands that the base class supports. To take advantage of any properties that are not statically defined, you can bind to the Properties property of the ViewModel and pass in a converter parameter for the name of the property you want to bind. For example, a ViewModel that looks like this: public class ExampleViewModel : ViewModelBase
{
public void Execute_MyCommand()
{
Set("Text", "Foo");
}
}
Can bind to the dynamic property and the convention-based command with the following XAML.
<TextBlock Text="{Binding Properties, Converter={StaticResource PropertiesConverter}, ConverterParameter=Text}" Margin="5" />
<Button Content="Execute MyCommand" Command="{Binding Properties, Converter={StaticResource PropertiesConverter}, ConverterParameter=MyCommand}" Margin="5" />
Of course, it is not as pretty as binding to Text and MyCommand like you can in WPF. But, it is better than having a failed feature. This allows you to share your ViewModels between WPF and Silverlight very easily.
<BeatDeadHorse>Hopefully, in Silverlight 5.0, we will see binding to dynamic properties more directly????</BeatDeadHorse>