Quote for the Week

"Learn to enjoy every moment of your life"

Thursday, February 5, 2015

ICommand Interface and RelayCommand Class in WPF MVVM

ICommand Interface and RelayCommand Class in WPF are commonly used for binding. ICommand Interface and RelayCommand class is implemented in the ViewModel and is exposed to the view controls.

Every view in the app has an empty codebehind file, except for the standard code that calls InitializeComponent in the class's constructor. In fact, you could remove the views' codebehind files from the project and the application would still compile and run correctly. Despite the lack of event handling methods in the views, when the user clicks on buttons, the application reacts and satisfies the user's requests. This works because of bindings that were established on the Command property of Hyperlink, Button, and MenuItem controls displayed in the UI. Those bindings ensure that when the user clicks on the controls, ICommand objects exposed by the ViewModel execute. You can think of the command object as an adapter that makes it easy to consume a ViewModel's functionality from a view declared in XAML.

When a ViewModel exposes an instance property of type ICommand, the command object typically uses that ViewModel object to get its job done.

We will try to understand ICommand Interface and RelayCommand Class with following example.

Create a View and ViewModel like following:

View: Lets create the view first.  Three things to note in this view

1. In this view, I have included MyWPFSample namespace

xmlns:local="clr-namespace:MyWPFSample"

2. I have set datacontext of the winodw to the MainWindowViewModel class present in MyWPFSample namespace

<Window.DataContext>
    <local:MainWindowViewModel/>
</Window.DataContext>    

3. I have done binding of the command of the button with the ButtonCommand property of MainWindowViewModel class.

Command="{Binding ButtonCommand}"

<Window x:Class="MyWPFSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:MyWPFSample"
        Title="MainWindow" Height="150" Width="370">
    <Window.DataContext>
        <local:MainWindowViewModel/>
    </Window.DataContext>
        <Grid>
        <Button Content="Click"
                Height="23"
                HorizontalAlignment="Left"
                Margin="77,45,0,0"
                Name="btnClick"
                VerticalAlignment="Top"
                Width="203"
                Command="{Binding ButtonCommand}"
                CommandParameter="Hai" />
    </Grid>
</Window>


ViewModel: ViewModel has namespace MyWPFSample, class as MainWindowViewModel and property as ButtonCommand. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Windows;

namespace MyWPFSample
{
    class MainWindowViewModel
    {
        private ICommand m_ButtonCommand;
        public ICommand ButtonCommand
        {
            get
            {
                return m_ButtonCommand;
            }
            set
            {
                m_ButtonCommand = value;
            }
        }
        public MainWindowViewModel()
        {
            ButtonCommand=new RelayCommand(new Action<object>(ShowMessage));
        }
        public void ShowMessage(object obj)
        {
            MessageBox.Show(obj.ToString());
        }
    }
}

When the user clicks on buttons, the application reacts and satisfies the user's requests. This works because of bindings that were established on the Command property of Button displayed in the UI. The command object acts as an adapter that makes it easy to consume a ViewModel's functionality from a view declared in XAML.

RelayCommand Class

In this example RelayCommand class is used for implementing ICommad object. I think it's a simple and standard approach.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;

namespace MyWPFSample
{
    class RelayCommand : ICommand
    {
        private Action<object> _action;
        public RelayCommand(Action<object> action)
        {
            _action = action;
        }
        #region ICommand Members
        public bool CanExecute(object parameter)
        {
            return true;
        }
        public event EventHandler CanExecuteChanged;
        public void Execute(object parameter)
        {
            if (parameter != null)
            {
                _action(parameter);
            }
            else
            {
                _action("Hello World");
            }
        }
        #endregion
    }
}

ICommand and RelayCommand keep track whether or not commands are available. If commands are not available, then all controls associated with that command are disabled. For example using command controls like button can be disabled if CanExecute() returns false. The Code that executes when command is invoked and is located in Execute event. handler. 

Tuesday, February 3, 2015

ref and out in c#.net

Ref and out parameters are used to pass an argument within a method. In this article, you will learn the differences between these two parameters.

Ref

The ref keyword is used to pass an argument as a reference. This means that when value of that parameter is changed in the method, it gets reflected in the calling method. An argument that is passed using a ref keyword must be initialized in the calling method before it is passed to the called method.

Out

The out keyword is also used to pass an argument like ref keyword, but the argument can be passed without assigning any value to it. An argument that is passed using an out keyword must be initialized in the called method before it returns back to calling method.

Program with ref and out keyword


public class Example
{
 public static void Main() //calling method
 {
 int val1 = 0; //must be initialized 
 int val2; //optional
 Example1(ref val1);
 Console.WriteLine(val1); // val1=1
 Example2(out val2);
 Console.WriteLine(val2); // val2=2
 }
 static void Example1(ref int value) //called method
 {
 value = 1;
 }
 static void Example2(out int value) //called method
 {
 value = 2; //must be initialized 
 }
}

Ref and out in method overloading


Both ref and out cannot be used in method overloading simultaneously. However, ref and out are treated differently at run-time but they are treated same at compile time. Hence methods cannot be overloaded when one method takes a ref parameter and other method takes an out parameter. The following two methods are identical in terms of compilation.

class MyClass
{
 public void Method(out int a) // compiler error “cannot define overloaded”
 {
 // method that differ only on ref and out"
 }
 public void Method(ref int a) 
 {
 // method that differ only on ref and out" 
 }
}

However, method overloading can be done, if one method takes a ref or out argument and the other method takes simple argument. The following example is perfectly valid to be overloaded.

class MyClass
{
 public void Method(int a) 
 {
 }
 public void Method(out int a)
 {
 // method differ in signature.
 }
}

Monday, February 2, 2015

Action and Func Delegates in C# .NET

The Func and Action generic delegates were introduced in the .NET Framework version 3.5.

Whenever we want to use delegates in our examples or applications, typically we use the following procedure:

  1. Define a custom delegate that matches the format of the method.
  2. Create an instance of a delegate and point it to a method.
  3. Invoke the method.
  4. But, using these 2 Generics delegates we can simply eliminate the above procedure.
  5. Since both the delegates are generic, you will need to specify the underlaying types of each parameters as well while pointing it to a function.

 For example Action<type,type,type……>

Action<>


  • The Generic Action<> delegate is defined in the System namespace of microlib.dll
  • This Action<> generic delegate, points to a method that takes up to 16 Parameters and returns void.


Func<>


  • The generic Func<> delegate is used when we want to point to a method that returns a value.
  • This delegate can point to a method that takes up to 16 Parameters and returns a value.
  • Always remember that the final parameter of Func<> is always the return value of the method. (For examle Func< int, int, string>, this version of the Func<> delegate will take 2 int parameters and returns a string value.)

Let's look at an example to see the use of both Delegates.

Create a new project named “FuncAndActionDelegates” and create a new class that holds all your methods.

MethodCollections.cs

class MethodCollections  
    {  
  
        //Methods that takes parameters but returns nothing:  
   
        public static void PrintText()  
        {  
            Console.WriteLine("Text Printed with the help of Action");  
        }  
        public static void PrintNumbers(int start, int target)  
        {  
            for (int i = start; i <= target; i++)  
            {  
                Console.Write(" {0}",i);  
            }  
            Console.WriteLine();  
        }  
        public static void Print(string message)  
        {  
            Console.WriteLine(message);  
        }  
  
        //Methods that takes parameters and returns a value:  
  
        public static int Addition(int a, int b)  
        {  
            return a + b;  
        }  
  
        public static string DisplayAddition(int a, int b)  
        {  
            return string.Format("Addition of {0} and {1} is {2}",a,b,a+b);  
        }  
  
        public static string SHowCompleteName(string firstName, string lastName)  
        {  
            return string.Format("Your Name is {0} {1}",firstName,lastName);  
        }  
        public static int ShowNumber()  
        {  
            Random r = new Random();  
            return r.Next();  
        }  
    }  


Program.cs

class Program  
    {  
        static void Main(string[] args)  
        {  
            Action printText = new Action(MethodCollections.PrintText);  
            Action<string> print = new Action<string>(MethodCollections.Print);  
            Action<int, int> printNumber = new Action<int, int>(MethodCollections.PrintNumbers);  
  
            Func<int, int,int> add1 = new Func<int, int, int>(MethodCollections.Addition);  
            Func<int, int, string> add2 = new Func<int, int, string>(MethodCollections.DisplayAddition);  
            Func<string, string, string> completeName = new Func<string, string, string>(MethodCollections.SHowCompleteName);  
            Func<int> random = new Func<int>(MethodCollections.ShowNumber);  
  
            Console.WriteLine("\n***************** Action<> Delegate Methods ***************\n");  
            printText();    //Parameter: 0 , Returns: nothing  
            print("Abhishek");  //Parameter: 1 , Returns: nothing  
            printNumber(5, 20); //Parameter: 2 , Returns: nothing  
            Console.WriteLine();  
            Console.WriteLine("**************** Func<> Delegate Methods *****************\n");  
            int addition = add1(2, 5);  //Parameter: 2 , Returns: int  
            string addition2 = add2(5, 8);  //Parameter: 2 , Returns: string  
            string name = completeName("Abhishek", "Yadav");    //Parameter:2 , Returns: string  
            int randomNumbers = random();   ////Parameter: 0 , Returns: int  
  
            Console.WriteLine("Addition: {0}",addition);  
            Console.WriteLine(addition2);  
            Console.WriteLine(name);  
            Console.WriteLine("Random Number is: {0}",randomNumbers);  
  
            Console.ReadLine();  
        }  

    }  

Output :