Continued adventure in Windows 8.1 Store App development

 

So if you have been following me lately, I have decided to start my first windows store application that my wife and I thought of. As any good developer would do, I have spent several weeks trying out the verious techniques Microsoft and other developers have used to develop applications and what the standard practice is for UI design and backend development.

Part of the backend development learning curve were PCL (Portable Class libraries). I will be doing a separate blog on that adventure as it can take up a whole day talking about it’s pros and cons. Today we discuss design time data for XAML projects. This was an interesting ride because the way the templates show you to do it is confusing at best and not what I would consider to be easy to duplicate.

Why bother with Design Time Data?

So first off, why bother with design time data at all? Isn’t it just a waste of time and time consuming? Well, the answer is yes, and no. The reason I say both is because it depends on what you are trying to do, like TDD for example. If you are just writing a quick application and most of your end users are other developers ( or anyone else that could care less what it looks like), then it most likely isn’t worth your time.

If however, you are looking to have a clean design and have the ability while you design the application to test things like word wrapping or look and feel without the need to debug your application, then design time data is right for you. I say this because you can use your real data (or fake data) to test how your layout will look with various data scenarios without the need to deploy or debug your application. The best part is, being design time, it’s real time.

So how does one go about doing this?

Well, that’s the interesting thing (sort of), there are several different ways to accomplish the design time technique. Iris Classon did an awesome post on 6 ways of setting design time data in Windows Store Apps. It’s an awesome example of how to set your project up to use design time data in several different ways. She even has examples to download. I will be focusing on how to this using JSON. The reason I chose this technique is for several reasons.

  • It is the most readable way (in my opinion) of how things are linked together between the backend and UI.
  • Can be type based. One thing I really like about this is the way you can hit F12 on the objects you link to in XAML  and it will take you to the class (more on this later).
  • It is very portable from one project to another.
  • It can be converted to use various other types of data for reading at design time (XAML)
  • Separation of Concerns from data to UI. This is always a biggie for me, but you can arguably say this for most of the Binding techniques in the UI.

Ok… So what did i learn

I learned that this sounded easy and it is, if you know what to do. I, of course did not, learning and all. I started first with the templates that come with VS 2013. I will tell you right now, you can use them for other things (like handling internal application events and assisting with things like your application being suspended or terminated), but for your own sanity, delete all the design time hooks. Either do it like I describe here, or one of the various ways that Iris mentions in the blog above. The way they use a generic Observable Collection and try to wire it up just makes things more confusing than they need to be when you are trying to understand this stuff.

So off  went, reading, watching various videos on channel 9. None of which really explained how you would go about doing design time data (also realize that I didn’t know at the time that this is what it was called! Now that I do, it was easier to find information on it).  The tutorial by Iris was a great start and after that, I found this awesome article that also dove into how to do everything with JSON.

To the Codemobile Robin

So, First thing you need to do is make 2 view models. one that will be the real one and one that will be the fake JSON one. They can be one in the same, I’m just showing this so that you can differentiate between the two.

Here is the real View Model ( ignore the interface)

RealViewModel

 

You will notice that this view model has properties Data and Color. This will be different from the JsonViewModel.

JsonViewModel

Now, this model does have the Data and Color properties by inheritance, but it also has a new property called name.

The JSON file (samplejson.json in my example) looks like this:

{

"Name":"Json Name",
"Data":"Json Data"
}

You will notice that Data is included here, but no Color property. I did this to how you the change at runtime of the background color. If you follow along, you will notice that it is not populated at design time.

The final backend code is on initialization of the application. This will fill the runtime bindings. In the MainPage.xaml.cs (code behind) you set the DataContext to a new Viewmodel since the properties were all just getters:

 /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            this.DataContext = new ViewModel();
        }
    }

 

Now for the XAML part. This is the meat and potatoes. Everything up to this point should be pretty obvious.

XAML Binding

 

If you look at the highlighted portions, you will notice the important parts. The first is xmlns:local=”using:…” This is used to define a variable that can be used to tie the models you wish to bind to. You will notice that mine is just the project name. This is because i have not put anything into subfolders in my projects. If you did, you would place the full namespace of where your view models live. The second is the DataContext. This is key for binding your actual Json data (which I have not shown yet). In my case, the JSON file is called samplejson.json. The model, as shown above is JsonModel and setting the IsDesignTimeCreateble property to True makes VS understand that you want this data loaded at design time. In the end, the string looks like this:

 d:DataContext="{d:DesignData Type=local:JsonViewModel, Source=samplejson.json,IsDesignTimeCreatable=True}"

NOTE: Make sure that this is included in your XAML file. If you don’t, VS is not going to know to ignore the blend namespace and the design binding will not work:

mc:Ignorable=”d”

The last portion below just creates a Grid with two textblocks inside a StackPanel. TheGrid has a the Background property set to Bind to the Color property. If you have been following along, you will notice that the color has not yet changed. This is because I did not set it in the JSON file, so design time is not picking it up. I encourage you to test it out and put a color in there to see what happens when you “Build” the project.

You will notice with the two TextBlocks that one has Name bound to it and the other is Data. The first one gets bound at design time and the other at runtime. If you look above, you will notice that both are populated as well as the color. This is because I already ran the application and it retrieved the “real data” from the ViewModel class.

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid Grid.Row="2" Grid.Column="0" Background="{Binding Color}" >
            <StackPanel Margin="5" HorizontalAlignment="Center" VerticalAlignment="Center">
                <TextBlock Text="XAML Data - design time data source set in JSON" FontSize="25"/>
                <TextBlock Text="{Binding Name}" FontSize="25"/>
                <TextBlock Text="{Binding Data}" FontSize="25"/>
            </StackPanel>
        </Grid>

 

One thing that is really neat that I said I would mention later above is that if you hit F12 (This is a shortcut for “Go to Definition”) on the Data or Name part of the Binding in XAML, it will take you right to the class file and property that it is Binding to. Very helpful in making sure things are binding to what you think they are.

I hope this has been informative and helps some of you developers out there figure this out without loosing any more hair like i did:)

As Always… happy Coding 🙂

Advertisements

About Gregg Coleman

I am Senior-level Software Engineer working primarily these days with .NET. I have a good working knowledge of ASP.NET MVC, Web Forms, WCF web services and Windows Services. I spend much of my time in the Web Services (SOAP and REST) world in my current job designing and implementing various SOA architectures. I have been in the software engineering industry for about 6 years now and will not now nor ever consider myself an "expert" in programming because there is always so much to learn. My favorite thing about designing software is there are always new emerging technologies and something to learn every day! My current job has me spending much of my job on the bleeding edge of technologies and changing gears all the time, so I'm never bored and always challenged. On my spare time I enjoy weight training, reading and venturing to new places near by. Of course programing and learning new technologies are another hobby of mine.
This entry was posted in .NET, .NET 4.5, C#, Classes, Computer Technology, DataAnnotation, Generics, Windows Phone, Windows Store Apps and tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s