Click here to Skip to main content
15,881,687 members
Articles / Silverlight

Silverlight Mobile: A Simple Workarorund to the Lack of a DataType Property on the DataTemplate Type?

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
15 Apr 2010GPL31 min read 9.9K   1
Silverlight Mobile: A Simple workarorund to the lack of a DataType property on the DataTemplate type?

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:

C#
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:

XML
<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.

XML
...
<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.

This article was originally posted at http://www.sunmetablog.co.uk?p=332

License

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


Written By
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? Pin
orloffm1-Jan-11 18:40
orloffm1-Jan-11 18:40 

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

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