Thursday, November 14, 2013

Safest way to use RaisePropertyChanged method - MVVM series 3 of n

Background

In my previous post on Simplest MVVM Ever, I gave the simplest overview of implementing MVVM. Now moving forward, I thought to extend my previous post by picking individual areas. And this time, I selected RaisePropertyChanged. All the developers working on XAML related apps are very well aware about the use of this RaisePropertyChanged. I am sure, most of us are also aware on where to use this. But does everyone aware about what is the proper way or let's say generic way to use it ??? Well, even if you are not aware, no problem. At the end of this post, you will surely take home a useful tip on using RaisePropertyChanged.

Introduction

As we know that MVVM provides a loose coupling methodology. At lot many places it is very useful to get benefit of such architecture, but at the cost of your alertness. Because when we are talking about MVVM, we usually says that ViewModel has no knowledge about View and properties are the way, who binds View and ViewModel to show the data on the UI. Here is the gotcha !!!
ViewModels implement INotifyPropertyChanged interface, so that the property changes in ViewModel can be passed onto View. Let's take a sample property, to understand in better way:
public string SelectedName
{
    get { return _selectedName; }
    set
    {
        if (_selectedName != value)
        {
            _selectedName = value;
            RaisePropertyChanged("SelectedName");
        }
    }
}
Point to note here is the hard coded name of the property "SelectedName" within the RaisePropertyChangedmethod. Now due to requirement change, one of the developer came and change the name of a property fromSelectedName to FirstName, and at the same time, he forgot to change the parameter of  RaisePropertyChanged method.  Now what will happen ???
This silly oversight will neither cause any compilation or run time errors, but our feature will simply not work. And such things are very difficult to detect until and unless there is a major break in functionality. So, now, how to get rid of such sort of issues???  

Tip comes here  

Instead of hard coding the property name, can't we go ahead and fetch the property name dynamically using Reflection APIs. Well, of course we can. 
Reflection.MethodBase.GetCurrentMethod().Name 
To implement it in better way, let's go ahead and create an extension method to read this property name as:
 public static string GetPropertyName(this System.Reflection.MethodBase methodBase)
{
    return methodBase.Name.Substring(4);
}
Here Substring method is required to get rid of 'get_' and 'set_' at the start depending upon where it is called. 
So, by using this extension method, one will be able to raise property changed events without concern that in future your property name might change.  MORE

Saturday, November 9, 2013

Simplest MVVM Ever - MVVM series 2 of n

Continuation to my previous article on WHY and WHEN of MVVM, this time, I am going to tell something on how we can create a simple MVVM application with minimal complexities. I am writing this article for those, who just want to see quickly how MVVM works. It doesn't do anything fancy and uses some basic databindings and commanding stuff. This article will be helpful for all those who are looking for a quick example of how to hook the View to the ViewModel and how commands plays a role. 
Today if you will surf internet, you will came across 1000s of articles discussing on what is MVVM and what are the major building blocks of it. So, I am going to repeat the same crazy thing again. But definitely, I'll brief you about major building blocks in layman, in order to make it easier to understand for beginners. Excited, eh ??? 
Layman introduction of building blocks  
So, let's quickly start with three main layers of MVVM.
  • Model - Model contains the classes which are similar to real world entities like Product, Customer, Student, Invoice, etc. It encapsulates business logic and data. Please note, Model classes do not directly reference view or in other way, Model classes have no dependency on view as how they are implemented. Technically speaking, Model classes are used in conjunction with a service or a repository that encapsulate data access.
  • ViewModel - Main purpose of ViewModel classes is to expose data to the view. It includes presentation logic and can be tested indepedently of Model. Similar to Model, ViewModel never reference View but it exposes properties and commands to bind the View data. In essence, ViewModel acts as a coordinator between View and Model.
  • View -  View deals only and only with appearance which one sees on screen. As a best practice, there should be no logic code in View classes, which need to be tested by unit test. In simple words, View's are meant only for UI visual behavior. 
I hope, till now, you might have got an idea of what is the responsibility of View, ViewModel and Model. Well, now before jumping onto coding part, I would like to brief you about some other points also, which needs to be handle for better and cleaner implementation of MVVM. 

Important components of any MVVM app

There are two main components which plays very vital role in implementing any application with MVVM. The first one is base class for ViewModel and second one is ICommand interface.
Base Class - There is some common stuff which is required for each and every ViewModel. So, in order to follow the good design, those common things should be placed in a base class and further this class can be derived by various ViewModels. Now question is, what this base class should contain?
This base class contains the implementation of INotifyPropertyChanged interface. As I mentioned earlier that, ViewModel cannot reference View directly. So, this interface bridges the gap between two and allows the messages to be passed to the View. The sample implementation of INotifyPropertyChanged is: 
public class ViewModelBase:INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void RaisePropertyChanged(string prop)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(prop));
        }
    }
} 
Please note, the above snippet is the basic one. So, if required, it can be expanded in various ways like addition of various validations like property name check, etc.
Well, let's move to ICommand interface.

ICommand interface - This interface provides very useful methods like Execute and CanExecute, which gives full control on commanding part. Commands are used by View to interact with ViewModel. Sample code is:
public class DelegateCommand : ICommand
{
     private Action<object> _action;
     public DelegateCommand(Action<object> action)
     {
         _action = action;
     }

    #region ICommand Members
    public event EventHandler CanExecuteChanged;
    public bool CanExecute(object parameter)
    {
        return true;
    }

    public void Execute(object parameter)
    {
        _action(parameter);
    }

    #endregion
}
I hope, this much knowledge is enough to proceed with simple MVVM example. 

Example scenario  

This is the example of Student entity and to keep it simple, I am taking only FirstName of a student. The list of students will be displayed on the screen. If user will select student name from the list and clicks on given button, then the selected name will be displayed in the textbox shown below. Isn't it simple???  

Model 

As I told, my model class is very simple here with 2 lines of code: 
public class Student
{
    public string FirstName { get; set; }
}

ViewModel

This class is bit complex than our Model. First let's have a look at the below snippet, then I'll talk more on it: 
public class StudentsViewModel:ViewModelBase
{
    public Student Student { get; set; }
    public ObservableCollection<Student> StudentList { get; set; }
    public string SelectedStudent { get; set; }

    private ICommand _updateStudentNameCommand;
    public ICommand UpdateStudentNameCommand
    {
        get { return _updateStudentNameCommand; }
        set { _updateStudentNameCommand= value; }
    }       

    public string FirstName
    {
        get { return Student.FirstName; }
        set
        {
            if (Student.FirstName != value)
            {
                Student.FirstName = value;
                RaisePropertyChanged("FirstName");
            }
        }
    }

    private string _selectedName;
    public string SelectedName 
    {
        get { return _selectedName; }
        set
        {
            if (_selectedName != value)
            {
                _selectedName = value;
                RaisePropertyChanged("SelectedName");
            }
        }
    }
    
    public StudentViewModel()
    {
        UpdateStudentNameCommand = new DelegateCommand(new Action<object>(SelectedStudentDetails));
        StudentList = new ObservableCollection<Model.Student> 
        { 
                new Student { FirstName = "Bruce" },
                new Student { FirstName = "Harry" },
                new Student { FirstName = "Stuart" },
                new Student { FirstName = "Robert" }
        };           
      }


    public void SelectedStudentDetails(object parameter)
    {
        if (parameter != null)
            SelectedName = (parameter as SimplestMVVM.Model.Student).FirstName;
    }
}
You might have notice that, we are inheriting ViewModelBase class, which provides the implementation ofINotifyPropertyChanged. Here I am exposing properties like FirstNameStudentList, andUpdateDetailsCommand which view can bind to. 
Well, let's take this one-by-one.
  • FirstName - This property is used to bind individual items of my ListView
  • StudentList - This property contains the list of first names and is set as a ItemSource of my ListView  
  • UpdateDetailsCommand - This property returns an ICommand using DelegateCommand class. This can be bind to anything like button press or key press. I hooked this command to my methodUpdateStudentDetails on button press, in order to update the text. 
That's all of the viewmodel. Now we can proceed for UI drawing. 

View 

Coming to view, by code behind is totally empty except for setting of DataContext as: 
public MainWindow()
{
    InitializeComponent();
}
And most of the UI related stuff is placed in XAML file itself 
<Window x:Class="SimplestMVVM.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SimplestMVVM.ViewModel"
Title="MVVM" Height="300" Width="300">
<Window.DataContext>
        <local:StudentsViewModel x:Name="ViewModel"/>
 </Window.DataContext>
<Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="0.878*"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
         </Grid.ColumnDefinitions>
                <StackPanel Grid.RowSpan="2">
        <ListView Name="ListViewStudentDetails" 
               Grid.Row="2" ItemsSource="{Binding StudentList}">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Name" 
                         DisplayMemberBinding="{Binding FirstName}"/>
                </GridView>
            </ListView.View> 
         </ListView>
        <Button Command="{Binding UpdateDetailsCommand}" 
          CommandParameter="{Binding ElementName=ListViewStudentDetails,Path=SelectedItem}"  
          Content="Update Text"/>
        <TextBlock FontWeight="Bold" Text="Selected student is: ">
          <Run Text="{Binding SelectedName, Mode=TwoWay}"/></TextBlock>
        </StackPanel>
    </Grid>
</Window>
MORE