Thursday, September 29, 2011

The Model-View-ViewModel (MVVM) Design Pattern


MVVM Pattern
The Model-View-ViewModel (MVVM) pattern helps you to cleanly separate the business and presentation logic of your application from its user interface (UI). Maintaining a clean separation between application logic and UI helps to address numerous development and design issues and can make your application much easier to test, maintain, and evolve. It can also greatly increase code re-use opportunities and allows developers and UI designers to collaborate more easily as they develop their respective parts of the application.

The MVVM pattern separates the UI of the application and the underlying presentation and business logic into three separate classes: the view, which encapsulates the UI and UI logic; the view model, which encapsulates presentation logic and state; and the model, which encapsulates the application’s business logic and data.

The MVVM pattern is a close variant of the Presentation Model pattern, optimized to take advantage of some of the core capabilities of WPF and Silverlight, such as data binding, data templates, commands, and behaviors.

In the MVVM pattern, the view encapsulates the UI and any UI logic, the view model encapsulates presentation logic and state, and the model encapsulates business logic and data. The view interacts with the view model through data binding, commands, and change notification events. The view model queries, observes, and coordinates updates to the model, converting, validating, and aggregating data as necessary for display in the view.

The following illustration shows the three MVVM classes and their interactions.


The MVVM classes and their interactions

 








As with all separated presentation patterns, the key to using the MVVM pattern effectively lies in understanding the appropriate way to factor your application’s code into the correct classes, and in understanding the ways in which these classes interact in various scenarios. The following sections describe the responsibilities and characteristics of each of the classes in the MVVM pattern.

The View Class

The view’s responsibility is to define the structure and appearance of what the user sees on the screen. Ideally, the code-behind file for a view contains only a constructor that calls the InitializeComponent method. In some cases, the code-behind file may contain UI logic code that implements visual behavior that is difficult or inefficient to express in Extensible Application Markup Language (XAML), such as complex animations, or the code needs to directly manipulate visual elements that are part of the view. You should not put any logic code in the view that you need to unit test. Typically, logic code in the view’s code-behind file will be tested by using a UI automation testing approach.

In Silverlight and WPF, data binding expressions in the view are evaluated against the view’s data context. In MVVM, the view’s data context is set to the view model. The view model implements properties and commands to which the view can bind and notifies the view of any changes in state through change notification events. There is typically a oneto-one relationship between a view and its view model.

Typically, views are Control-derived or UserControl-derived classes. However, in some cases, the view may be represented by a data template, which specifies the UI elements to be used to visually represent an object when it is displayed. Using data templates, a visual designer can easily define how a view model will be rendered or can modify its default visual representation without changing the underlying object itself or the behavior of the control that is used to display it.

Data templates can be thought of as views that do not have a code-behind file. They are designed to bind to a specific view model type whenever one is required to be displayed in the UI. At run time, the view, as defined by the data template, will be automatically instantiated and its data context set to the corresponding view model.

To summarize, the view has the following key characteristics:
• The view is a visual element, such as a window, page, user control, or data template.

• The view defines the controls contained in the view and their visual layout and styling.

• The view references the view model through its DataContext property. The controls in the view are data bound to the properties and commands exposed by the view model.

• The view may customize the data binding behavior between the view and the view model. For example, the view may use value converters to format the data to be displayed in the UI, or it may use validation rules to provide additional input data validation to the user.

• The view defines and handles UI visual behavior, such as animations or transitions that may be triggered from a state change in the view model or by the user’s interaction with the UI.

• The view’s code-behind file may define UI logic to implement visual behavior that is difficult to express in XAML or that requires direct references to the specific UI controls defined in the view.

The View Model Class

The view model in the MVVM pattern encapsulates the presentation logic and data for the view. It has no direct reference to the view or any knowledge about the view’s specific implementation or type. The view model implements properties and commands to which the view can bind data and notifies the view of any state changes through change notification events. The properties and commands that the view model provides define the functionality to be offered by the UI, but the view determines how that functionality is to be rendered.

The view model is responsible for coordinating the view’s interaction with any model classes that are required. Typically, there is a one-to many-relationship between the view model and the model classes. The view model might expose model classes directly to the view so that controls in the view can bind data directly to them. In this case, the model classes will need to be designed to support data binding and the relevant change notification events.

The view model may convert or manipulate model data so that it can be easily consumed by the view. The view model may define additional properties specifically to support the view. These properties would not normally be part of (or could not be added to) the model. For example, the view model may combine the value of two fields to make it easier for the view to be presented, or it may calculate the number of characters remaining for input in fields with a maximum length. The view model may also implement data validation logic to ensure data consistency.

The view model may define logical states the view can use to provide visual changes in the UI. The view may define layout or styling changes that reflect the state of the view model. For example, the view model may define a state that indicates that data is being submitted asynchronously to a web service. The view can display an animation while it is in this state to provide visual feedback to the user.
Typically, the view model will define commands or actions that can be represented in the UI and that the user can invoke. A common example is when the view model provides a Submit command that allows the user submit data to a web service or to a data repository.

The view might represent that command with a button so that the user can click the button to submit the data. Typically, when the command becomes unavailable, its associated UI representation becomes disabled. Commands provide a way to encapsulate user actions and to cleanly separate them from their visual representation in the UI.

To summarize, the view model has the following key characteristics:
• The view model is a non-visual class and does not derive from any WPF or Silverlight base class. It encapsulates the presentation logic required to support a use case or user task in the application. The view model is testable independently of the view and the model.
• Typically, the view model does not reference the view directly. It implements properties and commands to which the view can bind data. It uses the INotify PropertyChanged and INotifyCollectionChanged interfaces to generate change notification events that notify the view of any state changes.
• The view model coordinates the view’s interaction with the model. It may convert or manipulate data so that it can be easily consumed by the view, and it might implement additional properties that may not be present on the model. It may also use the IDataErrorInfo or INotifyDataErrorInfo interfaces to implement data validation.
• The view model may define logical states that the view can represent visually to the user.

The Model Class

The model in the MVVM pattern encapsulates business logic and data. Business logic is defined as any application logic that is concerned with the retrieval and management of application data and with making sure that any business rules that ensure data consistency and validity are imposed. To maximize re-use opportunities, models should not contain any use case–specific or user task–specific behavior or application logic.

Typically, the model represents the client-side domain model for the application. It can define data structures based on the application’s data model and any supporting business and validation logic. The model may also include the code to support data access and caching, although in most cases, a separate data repository or service is employed for this. Often, the model and data access layer are generated as part of a data access or service strategy, such as the ADO.NET Entity Framework, WCF Data Services, or WCF RIA Services.

Typically, the model implements the facilities that make it easy to bind to the view. This usually means that it supports property and collection changed notification through the INotifyPropertyChanged and INotifyCollectionChanged interfaces. Models classes that represent collections of objects typically derive from the ObservableCollection class, which provides an implementation of the INotifyCollectionChanged interface.

The model may also support data validation and error reporting through the IData ErrorInfo (or INotifyDataErrorInfo) interfaces. These interfaces allow WPF and Silverlight data binding to be notified when values change so that the UI can be updated. They also enable support for data validation and error reporting in the UI layer.

The model has the following key characteristics:
• The model classes are non-visual classes that encapsulate the application’s data and business logic. They are responsible for managing the application’s data and for ensuring its consistency and validity by encapsulating the required business rules and data validation logic.
• The model classes do not directly reference the view or view model classes and have no dependency on how they are implemented.
• The model classes typically provide property and collection change notification events through the INotifyPropertyChanged and INotifyCollectionChanged interfaces. This allows them to be easily data bound in the view. Model classes that represent collections of objects typically derive from the ObservableCollection class.
• The model classes typically provide data validation and error reporting through either the IDataErrorInfo or INotifyDataErrorInfo interfaces.
• The model classes are typically used in conjunction with a service or repository that encapsulates data access and caching.

Tuesday, September 20, 2011

Silverlight ListBoxItem Double Click Event

Following is the Code snippet for the List Box Item double click event using Silverlight 4:

XAML (MainPage.Xaml):
CODE(MainPage.Xaml.cs):

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Browser;
using System.Windows.Input;
namespace ListBoxDoubleClick
{
    public partial class MainPage : UserControl    {
        Point _clickPosition;
        public DateTime _lastClick = DateTime.Now;
        private bool _firstClickDone = false;
        public MainPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }
        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            for (int i = 1; i < 11; i++)
            {
                ListBoxItem lbitem = new ListBoxItem();
                lbitem.Name = "lb_" + i;
                lbitem.Content = "This is ListBoxItem No:" + i;
                lbitem.AddHandler(UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(ListBoxItem_DoubleClickEvent), true);
                listBox1.Items.Add(lbitem);
            }
        }
        private void ListBoxItem_DoubleClickEvent(object sender, MouseButtonEventArgs e)
        {
            ListBoxItem element = sender as ListBoxItem;
            if (element == null)
                return;
            DateTime clickTime = DateTime.Now;
            TimeSpan span = clickTime - _lastClick;       
            if (span.TotalMilliseconds > 300 || _firstClickDone == false)
            {
                //Single Click                lblMsg.Content = string.Format("ListBoxItem \" {0}\" is Single clicked. ", element.Content );
                _clickPosition = e.GetPosition(element);
                _firstClickDone = true;
                _lastClick = DateTime.Now;
            }
            else            {
                Point position = e.GetPosition(element);
                //Double Click                if (Math.Abs(_clickPosition.X - position.X) < 4 && Math.Abs(_clickPosition.Y - position.Y) < 4) //mouse didn't move => Valid double click                {
                    lblMsg.Content = string.Format("ListBoxItem \" {0}\" is Double clicked. ", element.Content);
                    /// Your logic goes here for double click event                    ///                 }
           
                _firstClickDone = false;
            }
        }
    }
}
SAMPLE OUTPUT: 






SOURCE DOWNLOAD LINK: 
ListBox Double Click