Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / Windows-Phone-7

Magical MVVM in WindowsStore Apps Using Expression Blend

4.76/5 (7 votes)
22 Jun 2014CPOL6 min read 13K   138  
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".

Image 1

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

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

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

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.

Image 2  

Image 3

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

Image 4

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,

Image 5

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.

Image 6

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.

Image 7

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.

Image 8

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.

Image 9

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

Image 10

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.

Image 11

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.

Image 12  

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

Image 13

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

Image 14

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.

Image 15

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)