Click here to Skip to main content
Click here to Skip to main content

Tagged as

Silverlight Mobile: A Simple workarorund to the lack of a DataType property on the DataTemplate type?

, 15 Apr 2010
Rate this:
Please Sign up or sign in to vote.
CodeProjectSo 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 t


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 eg: 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.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)

Share

About the Author

Steve Psaltis
Software Developer
United Kingdom United Kingdom
We cannot achieve perfection but we can strive for excellence. Excellence through creativity that pushes innovation, collaboration that facilitates productivity, knowledge that empowers people and persistence that eventually pays off !
 
Enjoy what you do and do what you enjoy !

Comments and Discussions

 
QuestionHow to use it as a ListBox ItemTemplate? Pinmemberorloffm1-Jan-11 18:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140827.1 | Last Updated 15 Apr 2010
Article Copyright 2010 by Steve Psaltis
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid