One common issue when using the MVVM pattern from a Silverlight 4 application is to have access to the current control’s data context from items controls’ data templates.
Let’s look at the following application :
It is composed of a data grid bound to a collection of books. Inside the view model that contains this collection, we can also find a command that displays books.
Here is the source code of this page, it’s view model and the book class :
What we want to do here is calling the ShowAuthorCommand command of the page’s view model passing it the current book as a parameter in order to do some sort of computing (here we will just display the book’s author in a MessageBox).
But if we execute the code above, the command is not invoked. The button used to invoke it is inside a data template and therefore, its data context is a book and not the page’s view model and so it is impossible to use the command directly.
The data template does not have access to the page’s view model but it has access to the static resources defined in the page.
What we will do with nRoute is to save the command inside a static resource at the page level and invoke it. This concept is not specific to nRoute and can be reimplemented in another way. I just think it is beautifully implemented in Route.
First we will create an instance of CommandRelay inside the page’s static resources (it is not the same and the RelayCommand from MVVMLightToolkit). You can translate the hereafter in english by “I declare a variable named ShowAuthorCommandRelay” :
Then inside the page’s behavior, in addition to the BridgeViewModelBehavior that maps the vue and its view model, we add a BridgeCommandBehavior that will initialise the instance of the CommandRelay previously declared :
The CommandRelay property is set to the CommandRelay to initialize and the CommandSource property is set to the command (here it’s the ShowAuthorCommand command from our view model).
You can translate the lines of code above in english by : “Initialize ShowAuthorCommandRelay with the ShowAuthorCommand command”.
Now we just need to invoke the command in the button using the following code :
We see that the syntax used to invoke the command has changed since our first try. Here we use the Command property of the ShowAuthorCommandRelay static resource. Because as previously said, we can access static resources from a DataTemplate.
If we execute the code corrected we can see that the MessageBox shows up correctly.
NB : In Silverlight 5, in this kind of scenario we would probably have used one of the new binding options known as RelativeSource AncestorType but the CommandRelay’s technique will still be valid.
As usual you can download the source code of the application on my skydrive.