Tuesday, 10 November 2015

Intro to MVVM light

Let us discuss about MVVM light used in the windows phone applications. This MVVM light was implemented to reduce the time to add code to the project. It is a toolkit which is developed to help the beginners to how to code in MVVM pattern. The definition of MVVM light is to accelerate the creation and development of MVVM applications in WPF, Silver-light, Windows Store, Windows Phone and Xamarin. You can refer the full document in this link.

The MVVM Light Toolkit adds the helper classes to the ViewModel by default when you install the MVVM package from the Nuget manager. It has ViewModelLocator and MainViewModel classes which helps the project to code in cleaner and easier. This MVVM light is easy to extend and manage the classes. It also creates testable applications and allows you to have thinner user interface in the view. It also maintains good security standards with some namespaces added to the library. This toolkit also help to open and edit the user interface into Blend. 

Difference between MVVM and MVVM light 

MVVM is a design pattern which is used to add code as per the patterns. i.e Our MainPage.xaml, BlankPage.xaml will be placed in View folder, Main_ViewModel.cs placed in ViewModel folder and Model.cs placed in Model folder. DataContext of the View is set with ViewModel class. MVVM is not only just file organization but also ensuring the code, is written as per the pattern too (separation of logic and all the nice stuff which should be implemented as per the pattern). We doesn't need any reference to design MVVM for our project

MVVM Light is mainly used when we need to communicate between multiple ViewModels. And we also have add on helper classes when we install MVVM light from Nuget manager as we already discussed above, given with a ViewModel folder.

How to install MVVM light to the existing project.

In your solution explorer - Add Reference - Manage Nuget packages - search for MVVM light and install to your project.

When you select install button after installing MVVM to the project it popups a dialog box with Accept and Decline button. This is to add the libraries to the project. Just select accept button.

You can see the references and classes added to the solution explorer.


Just extend your project with views and models. :)

Monday, 9 November 2015

Simple example for Observable collection

In our previous example we discussed about the simple examples of INotifyPropertyChanged, ICommand which are used in MVVM layout. Today let us discuss about Observable collection.

Observable Collection is nothing but it represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list will be refreshed. Follow this link to refer the description about Observable collection in MSDN.

There are two sentences we should consider here, “dynamic data collection”, and “provides notifications when items get added…”.

  1. Dynamic data is nothing but a list.  A collection of generic type <T> objects,  i.e it can keep a collection of any objects.
  2.  It provides notifications when items get added. This definition looks similar to INotifyPropertyChanged. It also notifies when the change is updated. ObservableCollection class is a built in implementation of a data collection that implements INotifyPropertyChanged.

If we use a list we should simply push notifications manually. Mainly  ObservableCollection itself only notifies for changes to the collection,. It is not for property changes of the individual objects in the collection.

Let us illustrate an example for Observable collection. In the previous example of INotifyPropertyChanged we created a Notify class and implemented interface. We gonna use the same class to extend our application to use Observable collection. Refer this link for the INotify class and add the below code


class Observ : ObservableCollection<Notify>
{
this.Add(new Notify { Title = "Myname", Desc = "fine", Year = 2014 });
this.Add(new Notify { Title = "Yourname", Desc = "good", Year = 2014 });
this.Add(new Notify { Title = "Yourday", Desc = "bad", Year = 2014 });
}


We should update our UI to display these items in the list view. So drag and drop the list view control. Add a data template to the listview to bind the text to the text blocks. Add the following code to list view control.

 <DataTemplate x:Key="MyDataTemp">
<StackPanel>
<TextBlock Text="{Binding Title}"/>
<TextBlock Text="{Binding Desc}"/>
<TextBlock Text="{Binding Year}"/>
</StackPanel>
</DataTemplate>

And just refer the key to the data template with the control name. It looks like
<ListView ItemTemplate="{StaticResource ListViewDataTemplate}" x:Name="lv1"/>

And the final step is done in code behind file. We should add the item source of the listview to the class..

Observ ob = new Observ();
lv1.ItemsSource = ob;

So in this way we can add the static data to the observable collections. It is the simplest way. We can also add the dynamic data using some api's where the data will be from requested url.

Thursday, 5 November 2015

Simple example for INotifyPropertyChanged

Data binding plays a vital role in developing applications with rich UI and neat coding. Data binding is the process that establishes a connection between the application UI(view) and main logic/business logic(i.e view model). Today let us discuss about some advanced concepts in data binding like INotifyPropertyChanged which is used in MVVM architecture. A interface which is used to update the UI with respect to the code using two way binding. Business logic/Main logic is the data which should be displayed on the UI and the also can be managed.

We can configure our data binding in four different ways

  • One way - causes changes to source
  • Two way - causes changes to source and target too.
  • Oneway to source  - reverse of one way binding
  • One time  - causes the source to initialize the target property, but changes do not propagate 

INotifyPropertyChanged uses System.ComponentModel namespace.

Create a class and add the below code

class Notify:INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private string title { get; set; }
        private int year { get; set; }
        private string desc { get; set; }

        public string Title
        {
            get { return title; }
            set{
                title = value;
                NotifyPropertyChanged("Title");
            }
        }
        public int Year
        {
            get { return year; }
            set
            {
                year = value;
                NotifyPropertyChanged("Year");
            }
        }
        public string Desc
        {
            get { return desc; }
            set
            {
                desc = value;
                NotifyPropertyChanged("Desc");
            }
        }
        protected void NotifyPropertyChanged(string propertyname)
        {
            if(PropertyChanged!=null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyname)); 
            }
        }

    }

When we add INotifyPropertyChanged after to the class name we can implement the interface by clicking below the blue dotted line. When we implement INotifyPropertyChanged we can see one event implemented

public event PropertyChangedEventHandler PropertyChanged;

We should bind these strings to the UI. Add the below code in the XAML file(Add your own properties for better view )

        <TextBlock Text="{Binding Title}"  Margin="22,10,0,35.75"/>
        <TextBlock Text="{Binding Desc}" Margin="22,10.25,0,35.5"/>
        <TextBlock Text="{Binding Year}" Margin="22,9.5,0,35.667"/>
        <Button Content="Click Me" Click="Button_Click" Margin="137,134.5,133,-109.333"/>
        <TextBox Text="{Binding Title, Mode=TwoWay}" />
        <TextBox Text="{Binding Desc, Mode=TwoWay}"  />
        <TextBox Text="{Binding Year, Mode=TwoWay}"  />
    </Grid>

Now to display the data in the page loaded add the below code.

        Notify n = new Notify();
        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            
            n.Title = "X-Men";
            n.Year = 2015;
            n.Desc = "good";
            this.DataContext = n;
        }

When we see the output the values will be displayed in the text box and text blocks. When we edit some thing in the text box the change will be affected in the text block, this is because of two way binding

We can also update our text in some button click events. While we work on real time data it will be more useful updating the values in the controls.

Tuesday, 3 November 2015

Simple example similar to MVVM layout

Today let us discuss  about a simple example in windows phone 8.1 apps with MVVM layout.

MVVM is mainly to separate the user interface ie view and the view model. This can be achieved by data binding. There are many classes used to maintain the standards of MVVM flow. Most of the developers use this MVVM architecture to design the applications mainly for some reasons. The code can be reusable. The unit testing is very easy if an application follows MVVM. Updates can be easily managed in the code.

It is possible to show a message dialog in a button click. This is done by generating a click event. But with out this click event we can display the message dialog by using command interfaces.

Similar to this example the developers follow this kind of models and views.

Drag and drop a button to the designer in windows phone 8.1 MainPage.xaml

Create a new class file and name it.

Now add the below code to the class file

In the below code CommandEx is the name of my class and ICommand is the interface. When we click on the blue dotted line down to the text we can implement the interface in our code. It adds CanExecute and Execute method with EventHandler.


class CommandEx:ICommand
    {
        public bool CanExecute(object parameter)
        {
            if (parameter != null)
            {
                return true;
            }
            else
                return false;
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            var msd = new MessageDialog(parameter.ToString()).ShowAsync();
        }
    }


So with the help of binding the code in the command will be executed.


    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    
    <Page.Resources>
        <local:CommandEx x:Key="ll"/>
    </Page.Resources>

    <Grid>
        <Button Content="Click"
                HorizontalAlignment="Left"
                Command="{StaticResource ll}"
                CommandParameter="Hello World"
                Margin="60,164,0,0"
                VerticalAlignment="Top"
                Height="42"
                Width="158"/>

    </Grid>

In the XAML code add page resource to use the class (CommandEx). Define a key and use that key in the button, binding to the command. Here the command parameter is from the execute method defined in the class.

Monday, 2 November 2015

Introduction to MVVM for Windows phone 8.1


Model-View-ViewModel is developed by Ken Cooper and Ted Peters. It is mainly developed to simplify the event driven programming(i.e the mouse buttons clicks, key down, key up events)etc. 

Why MVVM?

It is mainly to separate the view and model in the applications. When our application needs to be changed without changing design of our application we can change the model. 

For example: When an application is updated from one version to other if the application uses MVVM architecture it happens easy to modify their code. 

Reusability of the classes, make the code light and efficient, bind the data from view to model and make the updates to the design with out  any changes.

It is easy to test the application when the developers follow MVVM architecture.

For a simple application it is not necessary to use MVVM architecture while it makes the code very complex. Assume an application with a buuton and textblock to display the text in button click it is not necessary to follow MVVM architecture. Because we are not adding any values or not updating the view.

In MVVM the data gets from other source like database, webservice or while we bind the data in the ViewModel to the view.

While we explain about MVVM these terms play a crucial role. They are
Model
View
ViewModel



Model is the core that implements the main logic of the view and view model. For example some classes defined in the model is used in the viewmodel.  

View is the user interface of the application.Data Binding plays the vital role .

View model is the layer of abstraction between the view and model. The entire logic is done in this view model.