Click here to Skip to main content
11,712,454 members (75,225 online)
Click here to Skip to main content

Magical MVVM in WindowsStore Apps Using Expression Blend

, 22 Jun 2014 CPOL 5.5K 104 13
Rate this:
Please Sign up or sign in to vote.
Magical MVVM using power of Expression Blend

Are you developing applications for Windows Store? Have to tried Using Expression Blend for developing your application. Expression Blend for Windows Store apps can be really valuable doing MVVM (Model View View Model). How can you use magic of BLEND for doing MVVM?  Lets dig in.

Getting Started

So you are ready to watch magic of Expression Blend for Windows Store Applications. Lets create a blank project for Windows Store apps.

After you have created an empty project, then create some folders that are "Models" , "Views" and "View Models".

place "MainPage.xaml" in "Views" folder so may become easier for managing the views , models and view models.

Creating Models

Now its time to create some models for your application. In this project I have taken Colors as my personal choice. As I have chosen Colors lets make it's respective models that are , "ColorInfo" and "GroupInfo". "ColorInfo" consists of the information a color would contain.

Here is respective code for the ColorInfo Model,  

C#:

  public class ColorInfo
    {
        public Color Color { get; set; }
        public string Name { get; set; }
        public SolidColorBrush Brush { get { return new SolidColorBrush(this.Color); } }
    }<!--[if IE]>

<![endif]-->

it contains the Name of Color and its other respective information.

The very second model would be the "GroupInfo". It would have Array of type "ColorInfo"
 and is a group basically.

C#:

public class GroupInfo
{
    public string Name { get; set; }
    public ColorInfo[] Colors { get; set; }
}

Wonderful, you are now done with the "Models" not its time to dig into the "ViewModels".

Creating ViewModels

So now its time to create the "ViewModels". For this very project we would create only one "ViewModel" that would be "MainPageViewModel". In this ViewModel I have used LINQ for getting colors from the "Colors" class and have made groups each of  "Five".

C#:

 public class MainPageViewModel 
    {
        public MainPageViewModel()
        {
            var colors = typeof(Colors)
                .GetRuntimeProperties().Select(x => new ModelsColorInfo
                {
                    Name = x.Name,
                    Color = (Color)x.GetValue(null)
                });
            this.Groups.Add(new GroupInfo { Name = "Group 1", Colors = colors.Skip(00).Take(5).ToArray() });
            this.Groups.Add(new GroupInfo { Name = "Group 2", Colors = colors.Skip(05).Take(5).ToArray() });
            this.Groups.Add(new GroupInfo { Name = "Group 3", Colors = colors.Skip(10).Take(5).ToArray() });
            this.Groups.Add(new GroupInfo { Name = "Group 4", Colors = colors.Skip(15).Take(5).ToArray() });
            this.Groups.Add(new GroupInfo { Name = "Group 5", Colors = colors.Skip(20).Take(5).ToArray() });    
        }

        ObservableCollection<Models.GroupInfo> _Groups = new ObservableCollection<Models.GroupInfo>();
        public ObservableCollection<Models.GroupInfo> Groups { get { return _Groups; } }       
    }

    public abstract class BindableBase : System.ComponentModel.INotifyPropertyChanged
    {

        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
        protected void SetProperty<T>(ref T storage, T value, [System.Runtime.CompilerServices.CallerMemberName] String propertyName = null)
        {
            if (!object.Equals(storage, value))
            {
                storage = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new System.ComponentModelPropertyChangedEventArgs(propertyName));
            }
        }
        protected void RaisePropertyChanged([System.Runtime.CompilerServices.CallerMemberName] String propertyName = null)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new System.ComponentModelPropertyChangedEventArgs(propertyName));
        }
    <!--[if IE]>

<![endif]-->

That was all for ViewModels and Models. Now it's time to change the IDE that is our beloved BLEND.

Its Blend Time:(Complete Design in BLEND)

Now it's time for Expression Blend to show it's magic. It is really easy to design your application after you have created your Models and View Models respectively. As you have shifted to ExpressionBlend. Go to the "DateTab" of Expression Blend, there at bottom there would be a Tab for DataContext.

 

Click on "Set design-time DataContext" you would be followed by a PopUp.

Select the "DataContext Type" to "DesignInstance",
as you do this you would be followed by the number of classes. Find "MainPageViewModel" , if you are unable to find it. This thing happens sometime in Expression Blend and that is because the solution has been compiled in Visual Studio but it hasn't been Build inside Blend. To resolve it, take help of "Ctrl + Shift + Build". As you build the very project inside Blend you would find "MainPageViewModel" in your list. Select that!

Note: Don't forget to check the "IsDesignTimeCreatable".

As you follow the procedure, you would notice a change in the very TAB. It would look something like this,

So now here you have "Groups" and "Colors"

"Groups" here are on the GroupInfo Class we made in Model. It contained ColorInfo the is here named as "Colors".  Here we would now drag the Colors and drop it over the MainPage.

Wolahh!! so you see here that Groups are automatically formed. It has an issue in it. We can see the color's name but there is a label extra and the color of the "Color named" is not shown in the Item Created. To design it accordingly we need to do following  

  1. Right Click over the Item
  2. Go Over Edit additional Template
  3. Edit Generated Item
  4. Then over "Edit Current"

Now notice at the "Objects&Timeline" tab, you would notice that would look similar to this.

Here, we have a stack panel that has two TextBlocks. In the Border we have an "Image". Actually we don't need any image here so we would simply remove that. Now Click over "Border" and shift your concentration to the  "Properties Tab" and do the following,

  1. Click on the Small Green Box at the end of Back Ground color.
  2. Now Click on Create DataBinding.
  3. Select Colors and in it SolidColorBrush

You are done, now you would notice that colors would appear in Boxes. Delete the extra TextBlock from "Objects&Timeline" that is placed inside the stackpanel.

Now its time to make the items more beautiful. Select the "Grid" from objects and timelines Tab and reduce it's height so the it looks a bit more nice.

Now give some margin from left top so the it does now spread all over the screen edges, for this purpose click over the MainPage and go over to properties. Here in margin give the upper and the left margin value that you like. In my case the very value is "33".

So our design has been completed. But what if we add a Semantic Zoom control in our application? Well that's not a bad idea.

Adding Semantic Zoom

Semantic Zoom is a control that is available in Windows 8.1 SDK. It's really easy to add Semantic Zoom using Blend. Go to the Assets tab at left top and Select semantic zoom control for "Controls.

Drag it and drop it over Grid in the "Objects&Timeline" Tab.
Semantic Zoom has Two View inside it

  1. ZoomIn View
  2. ZoomOut View

ZoomIn View it the current of default view of the application whereas the ZoomOut view is the View when user clicks the "minus button (at right bottom of metro apps)" to see the groups.

Note:
ShortCuts for ZoomIn and ZoomOut are
Ctrl & '+'
Ctrl & "-"

For the ZoomIn View we have already developed the GridView, so delete the "GridView" inside the ZoomInView and drag your default "GridView" to the ZoomInView Catagory.

 

For ZoomOut View select the "GridView" and follow these steps,

  1. Go Over DataContext tab
  2. Drag the Groups to the Screen
  3. You would notice that Groups would appear on screen

after you see that Groups have appeared on screen you have to do this,

  1. Right Click over the Item
  2. Go Over Edit additional Template
  3. Edit Generated Item
  4. Then over "Edit Current"

Now here is one really important thing, select the border for "Object and Timeline", Delete the Picture and select the Border only. Go to the properties and Click over small green button at end of Back Ground Color. Select the "Create Data Binding".Now here there are Groups you need to bind it with the very first color inside that Group, we call call it as Color[0].

so, select the SolidColorBrush of Color[0], you can also select any color by changing that [0]. As you do the binding you would notice that the groups would appear like following.

Isn't that amazing? All of your application is designed using Blend. I hope you enjoyed this tutorial.

Source Code

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Saad_Mahmood
User Interface Analyst Procesium
Pakistan Pakistan
Expressions Blend Guy from Pakistan. Trying to make .NET developer's life easier by use of BLEND during their development.

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 5 Pin
deshjibon15-Jul-14 9:34
memberdeshjibon15-Jul-14 9:34 
GeneralMy vote of 5 Pin
ishihidul14-Jul-14 14:59
memberishihidul14-Jul-14 14:59 
QuestionYour sample Model and ViewModel code has HTML embedded Pin
Chris Marassovich24-Jun-14 20:20
memberChris Marassovich24-Jun-14 20:20 

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 | Terms of Use | Mobile
Web03 | 2.8.150819.1 | Last Updated 23 Jun 2014
Article Copyright 2014 by Saad_Mahmood
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid