Brian Genisio's House of Bilz

  Home  |   Contact  |   Syndication    |   Login
  72 Posts | 0 Stories | 186 Comments | 0 Trackbacks

News

Locations of visitors to this page

Archives

Post Categories

Who am I?

Friday, May 14, 2010 #

More Adventures in MVVM Shout it kick it on DotNetKicks.com

EDIT: Here is why I love blogging and sharing code so much: Putting your ideas and code out into the public space always manages to add value to the ideas that were originally posted.  Case in point: Tobias Richling commented on this post with a fantastic refinement to the Silverlight dynamic property binding.  There is a much more simple way to bind against these dynamic properties (including automatic commanding) than my first approach.  I have incorporated the changes to the CodePlex site and I have edited this post to reflect the changes.  Thanks again, to Tobias for the suggestion.

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 there is a workaround.  In the Silverlight version of my base class, I include a string indexer for getting and setting properties that lets you bind to dynamic properties in the ViewModelBase, especially the convention-based commands that the base class supports.

For example, with a View Model that looks like this:

public class ExampleViewModel : ViewModelBase
{
    public void Execute_MyCommand()
    {
        Set("Text", "Foo");
    }
}

The view can bind to the dynamic property (Text) and the convention-based command (MyCommand) with the following XAML.

<TextBlock Text="{Binding [Text]}" Margin="5" />
<Button Content="Execute MyCommand" Command="{Binding [MyCommand]}" Margin="5" />

Notice the square brackets around the name of the property.  Of course, it is not as perfect 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>