So what’s the problem? Well, I want to be able to write Silverlight applications whilst obeying the MVVM philosophy just like I do in WPF and that means no code behind where possible. So here is what I came up with on a Sunday evening! If anyone has any other solutions, I would love to hear/see them. Please excuse the naming of my Views
and ViewModels
, I had watched Tim Heuer and Craig Shoemaker on MVVM for Silverlight just moments before and this was their case study. By the way, please watch this first as it explains very nicely how you can implement MVVM in a simple way if you are not too bothered about having a little code behind in your views (ignoring the technical errors, e.g.: TwoWay
being the default binding Mode!).
So I created an Attached
Property (of course !) which looks like this:
public class TemplatedContentControl : ContentControl
{
public static readonly DependencyProperty TemplatedContentProperty =
DependencyProperty.RegisterAttached(
"TemplatedContent",
typeof(object),
typeof(TemplatedContentControl),
new PropertyMetadata(OnPropertyChanged));
private static void OnPropertyChanged(object sender,
DependencyPropertyChangedEventArgs args)
{
if (args.NewValue == null)
return;
var content = sender as ContentControl;
var typeKey = args.NewValue.GetType().Name;
if (GetTheContentsDataTemplate(typeKey) == null)
{
throw new InvalidOperationException(
string.Format(
"No DataTemplate resource exists with the key {0}",
typeKey));
}
content.Content = args.NewValue;
content.ContentTemplate =
Application.Current.Resources[typeKey] as DataTemplate;
}
private static DataTemplate GetTheContentsDataTemplate(string key)
{
return Application.Current.Resources[key] as DataTemplate;
}
public static void SetTemplatedContent(
DependencyObject obj, string tabStop)
{
obj.SetValue(TemplatedContentProperty, tabStop);
}
public static object GetTemplatedContent(DependencyObject obj)
{
return (object)obj.GetValue(TemplatedContentProperty);
}
}
This is really quite simple: When I set the content of my content control, I just grab the type name of the content binding and try and find a DataTemplate
that matches, which I am expecting to be a DataTemplate
. I then set the ContentTemplate
to be the DataTemplate
and set the actual content which takes care of the DataContext
.
In my App.xaml, I then need to define the DataTemplate
that has a key name that matches the content type name:
<DataTemplate x:Key="SimpleMathGameViewModel">
<Views:SimpleMathGameView/>
</DataTemplate>
I can then add a ViewModel
to my views and the visual representation of that ViewModel
is taken care of by DataTemplates
. Which is more like what I am used to.
...
<Grid x:Name="ContentGrid" Grid.Row="1">
<AttachedProperties:TemplatedContentControl
TemplatedContent="{Binding Path=CurrentGame}"/>
</Grid>
...
Suddenly, I feel more at home with my WPF slippers back on! I will try and create a screen cast on this one.