Thursday, June 30, 2011

Silverlight 4 - Programmatically invoking command's CanExecute status

While developing Silverlight 4 applications with Model-View-ViewModel (MVVM), one of the feature that comforts developers is the command object that implements from ICommand. The ICommand interface exposes two methods Execute and CanExecute and an event CanExecuteChanged. As the name implies, the Execute method is the one to be executed when the command is invoked and CanExecute is the method that specifies the execution status - means, it influences whether the command can be executed or not. For getting core details of ICommand, please refer msdn.

Points to be considered while implementing ICommand
Upon implementing the ICommand, simply what we'll be doing is,
  • Get two delegates that matches the Execute and CanExecute methods' signatures(Action<object> and Func<object, bool> resp) as parameters in the constructor and store them in a locally in the class level scope.
  • Then invoke those delegates in the respective methods. That is Action delegate (Action<object>) in the Execute method and the function delegate (Func<object, bool>) in the CanExecute method.
  • In addition to invoking the action delegate (Action<object>), the Execute method need to call the CanExecute method.
  • In addition to invoking the function delegate (Func<object, bool>), the CanExecute method need to raise the CanExecuteChanged event.
There exists several examples in web on implementing ICommand interface and using it. One such is provided by John Papa here, which details more about commanding.

In Silverlight 4, ButtonBase and Hyperlink supports commanding.

The CanExecute method plays its role visually by enabling or disabling the control it(the command object) is bound to. That is the reason why the CanExecute method is called from the Execute method as it'll validate the execution status at the time of execution.

Now comes the core of this post: From the above explanation it is clear that the CanExecute method is called on the command action of the bound control (example: on click of the control). But in some scenarios, we might need to make a strategy somehow that the CanExecute method need to be invoked in order to reevaluate the execution status. Such scenario arises when changes from some other manipulation affects the logic we use to arrive the return value of CanExecute method. Say as a result of some manipulation your ViewModel changes a property which is used in the CanExecute method. So now you need to programmatically achieve reevaluation of the execution status.

Triggering CanExecuteChanged event will do this for you. Hence its good to have a public method in the class that implements the ICommand to raise the CanExecuteChanged event.

Snippet 1

public void RaiseCanExecuteChanged()
{
    if (CanExecuteChanged != null)
    {
        CanExecuteChanged(this, new EventArgs());
    }
}

Hence RaiseCanExecuteChanged is also one of the important point to be considered when implementing the ICommand, as such scenarios are common in applications with MVVM that uses command.

Additional Info
Prism provides this ICommand implementation through DelegateCommand class, which also exposes the RaiseCanExecuteChanged method.

References
http://msdn.microsoft.com/en-us/library/system.windows.input.icommand(v=vs.95).aspx
http://johnpapa.net/5-simple-steps-to-commanding-in-silverlight

Tuesday, June 28, 2011

Silverlight 4 Printing Centered

In one of my previous article, I've explained about printing fit to page in Silverlight 4(Silverlight4 - Printing fit to page). In this article, I'll enhance the PrintUtility(specified in the Snippet 2 of post) to print the element centered in the print area(center of the paper).

Let us recap the idea of printing fit to page. 
  1. The print element is transformed (scaled) to fit to page, when the print element size exceeds the print area - Scaled.
  2. The print element is printed as it is otherwise - Normal.
During scale transformation, the print element is scaled in such a way to maintain the aspect ratio. So it is clear that we need to handle both the scenarios (Scaled & Normal) while centering the print element.

Ok, now we need to identify how much the print element need to be positioned left and top. A simple calculation will do that for us.

Left position = ((total print area width) - (print element width)) / 2, Top position = ((total print area height) - (print element height)) / 2.

Initially I thought of setting the margin to the print element to achieve centering. But after that I got an alternate way from an article. As most of you know three primary transformations are Transformation, Rotation and Scaling. It is the translate transformation that we're going to use for centering.

Change will be there only in the DocToPrint_PrintPage handler with respective calculations and transformation included. Below is the complete code snippet of the PrintUtility.

Snippet 1

public class PrintUtility
{
    #region Class Level Variables

    private const string NullReferenceExceptionMessage = "PrintElement is null : Please specify the element to be printed.";

    private Grid parentGrid;

    private Border borderItem;

    private BusyIndicatorControl busyIndicatorControl;

    private WriteableBitmap printElementImage;

    private ImageBrush printElementImageBrush;

    #endregion

    #region Events

    #endregion

    #region Properties

    public FrameworkElement PrintElement { get; private set; }

    public string DocumentName { get; private set; }

    public FrameworkElement TabletUIElement { get; set; }

    #endregion

    #region Constructors

    public PrintUtility(FrameworkElement elementToBePrinted, string documentName)
    {
        this.PrintElement = elementToBePrinted;
        this.DocumentName = documentName;
    }

    #endregion

    #region Event Handlers

    private void DocToPrint_EndPrint(object sender, EndPrintEventArgs e)
    {
        this.PrintElement.RenderTransform = null;

        if (this.borderItem != null)
        {
            if (this.parentGrid.Children.Contains(this.borderItem))
            {
                this.parentGrid.Children.Remove(this.borderItem);
            }

            this.borderItem = null;
        }

        this.parentGrid = null;
        this.printElementImage = null;
        this.printElementImageBrush = null;
    }

    private void DocToPrint_BeginPrint(object sender, BeginPrintEventArgs e)
    {
        FrameworkElement maskElement = this.TabletUIElement ?? this.PrintElement;

        if (maskElement.Parent is Grid)
        {
            this.parentGrid = (Grid)maskElement.Parent;
            this.parentGrid.Children.Add(this.BuildBorderWithImageFill());
        }
    }

    private void DocToPrint_PrintPage(object sender, PrintPageEventArgs e)
    {
        double scale = 1;
        TransformGroup transformGroup = new TransformGroup();

        if (e.PrintableArea.Height < this.PrintElement.ActualHeight)
        {
            scale = e.PrintableArea.Height / this.PrintElement.ActualHeight;
        }

        if (e.PrintableArea.Width < this.PrintElement.ActualWidth && e.PrintableArea.Width / this.PrintElement.ActualWidth < scale)
        {
            scale = e.PrintableArea.Width / this.PrintElement.ActualWidth;
        }

        if (scale < 1)
        {
            ScaleTransform scaleTransform = new ScaleTransform();
            scaleTransform.ScaleX = scale;
            scaleTransform.ScaleY = scale;

            TranslateTransform translateTransform = new TranslateTransform();
            translateTransform.X = (e.PrintableArea.Width - (this.PrintElement.ActualWidth * scale)) / 2;
            translateTransform.Y = (e.PrintableArea.Height - (this.PrintElement.ActualHeight * scale)) / 2;

            transformGroup.Children.Add(scaleTransform);
            transformGroup.Children.Add(translateTransform);
        }
        else
        {
            TranslateTransform translateTransform = new TranslateTransform();
            translateTransform.X = (e.PrintableArea.Width - this.PrintElement.ActualWidth) / 2;
            translateTransform.Y = (e.PrintableArea.Height - this.PrintElement.ActualHeight) / 2;

            transformGroup.Children.Add(translateTransform);
        }

        this.PrintElement.RenderTransform = transformGroup;
        e.PageVisual = this.PrintElement;
    }

    #endregion

    #region Public Methods

    public void Print()
    {
        if (this.PrintElement != null)
        {
            PrintDocument docToPrint = new PrintDocument();

            docToPrint.PrintPage += new EventHandler<PrintPageEventArgs>(this.DocToPrint_PrintPage);
            docToPrint.BeginPrint += new EventHandler<BeginPrintEventArgs>(this.DocToPrint_BeginPrint);
            docToPrint.EndPrint += new EventHandler<EndPrintEventArgs>(this.DocToPrint_EndPrint);

            docToPrint.Print(this.DocumentName);
        }
        else
        {
            throw new NullReferenceException(NullReferenceExceptionMessage);
        }
    }

    #endregion

    #region Private Methods

    private BusyIndicatorControl BuildBusyIndicatorControl()
    {
        this.busyIndicatorControl = new BusyIndicatorControl();

        this.busyIndicatorControl.IsBusy = true;
        this.busyIndicatorControl.BusyContent = "Processing For Printing......";

        return this.busyIndicatorControl;
    }

    private Border BuildBorderWithImageFill()
    {
        this.printElementImageBrush = new ImageBrush();
        this.borderItem = new Border();

        this.printElementImage = new WriteableBitmap(this.TabletUIElement ?? this.PrintElement, null);
        this.printElementImageBrush.ImageSource = this.printElementImage;

        this.borderItem.Background = this.printElementImageBrush;
        this.borderItem.Child = this.BuildBusyIndicatorControl();

        return this.borderItem;
    }

    #endregion
}


Thursday, June 23, 2011

Silverlight 4 ComboBox SelectedItem vanishes on ItemsSource update

In Silverlight 4, the SelectedItem is set to null when we update / change (new instance set) the ItemsSource.

Let us take a case of having a readonly property that builds a new list(by performing operations like filtering , sortings, etc... on an existing data) each time the property is read(get).

Snippet 1
 
ObservableCollection<ICheckItem> checkItemCollection;

public ObservableCollection<ICheckItem> CheckItemCollection
{
    get
    {
        return checkItemCollection;
    }
    set
    {
        checkItemCollection = value;
        checkItemCollection.CollectionChanged += (s, e) =>
        {
            NotifyPropertyChanged("SortedCheckItemCollection");
        };
        NotifyPropertyChanged("CheckItemCollection");
        NotifyPropertyChanged("SortedCheckItemCollection");
    }
}

public List<ICheckItem> SortedCheckItemCollection
{
    get
    {
        return CheckItemCollection.OrderBy(ci => ci.Name).ToList();
    }
}
 
Also consider another property that holds the selected item.
 
Snippet 2
 
ICheckItem selectedCheckItem;
public ICheckItem SelectedCheckItem
{
    get
    {
        return selectedCheckItem;
    }
    set
    {
        selectedCheckItem = value;
        NotifyPropertyChanged("SelectedCheckItem");
    }
}
 
Now if we bind the above properties to the ComboBox, initially the ComboBox will hold the list and displays the selected item correctly, provided the SelectedItem property holds a valid object(item) from the ItemsSource(IEnumerable).
 
Snippet 3

<ComboBox ItemsSource="{Binding Path=SortedCheckItemCollection}" DisplayMemberPath="Name" SelectedItem="{Binding Path=SelectedCheckItem, Mode=TwoWay}" />
<br />

But after that, the next time when the property change notification for "SortedCheckItemCollection" is raised(by some means), the ItemsSource is provided with a new List instance by the "get" accessor(see Snippet 1). At this point of time, the SelectedItem will become null and no item will be displayed selected in the ComboBox.
 
To overcome this issue(in my real case), I planned to go with the custom control derived from the ComboBox. In the beginning, I thought of providing a dependency property that works in sync with the SelectedItem property and make workaround for the scenario where the issue arises. But while developing code for that, I identified(by debugging) that only after the execution of "OnItemsChanged" handler, the SelectedItem is lost.
So I revamped my logic by overriding the "OnItemsChanged".
In that I'll,
  • Persist the SelectedItem locally,
  • Call the base.OnItemsChanged and
  • Then reset the SelectedItem with the locally persisted object.

Snippet 4

/// <summary>
/// PersistenceComboBox is same as ComboBox in addition will handle the SelectedItem when the ItemSource is changed.
/// Workaround for issue: ComboBox unable to handle the SelectedItem on ItemSource change. 
/// </summary>
public class PersistenceComboBox : ComboBox
{
    /// <summary>
    /// Updates the current selected item when the <see cref="P:System.Windows.Controls.ItemsControl.Items"/> collection has changed.
    /// </summary>
    /// <param name="e">Contains data about changes in the items collection.</param>
    protected override void OnItemsChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        object persistenceSelectedItem = null;

        foreach (object item in this.ItemsSource)
        {
            if (item.Equals(this.SelectedItem))
            {
                persistenceSelectedItem = item;
            }
        }

        base.OnItemsChanged(e);

        if (this.SelectedItem != persistenceSelectedItem)
        {
            this.SelectedItem = persistenceSelectedItem;
        }
    }

}

So the change in the XAML(Snippet 3) will be,
 
Snippet 5 
 
<customControl:PersistenceComboBox ItemsSource="{Binding Path=SortedCheckItemCollection}" DisplayMemberPath="Name" SelectedItem="{Binding Path=SelectedCheckItem, Mode=TwoWay}" />
<br /> 

Now, the PersistenceComboBox(custom control) can be used in places where we require the SelectedItem to be retained even after updating the ItemsSource.

Saturday, May 28, 2011

WCF Duplex Message Exchange Pattern - Simple sample

This post just explains how to create a simple WCF service of Duplex MEP(Message Exchange Pattern).
  • Two Service contracts need to be created.
  • First, create a Callback contract which the client will implemnt. The service will use this Callback contract to call the client back.
  • Then as for other WCF services create a Service contract and associate the Callback contract to this Service contract using the CallbackContract property of the Service contract attribute.
  • Specify the Operation contracts as "OneWay".
  • Session is required(enabled by default).
  • Get a channel to the current client instance using OperationContext.Current.GetCallbackChannel<>() to call the callback methods.
  • Configure the service with the wsDualHttpBinding.
Snippet 1 - Service Contract

namespace DuplexWcfService1
{
    [ServiceContract]
    public interface IAddHandler
    {
        [OperationContract(IsOneWay = true)]
        void Resultant(double result);
    }

    [ServiceContract(Namespace = "DuplexWcfService1", CallbackContract = typeof(IAddHandler))]    
    public interface IAddService
    {
        [OperationContract(IsOneWay = true)]
        void Add(double param1, double param2);
    }
}

Snippet 2 - Service Implementation

namespace DuplexWcfService1
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
    public class AddService : IAddService
    {
        public void Add(double param1, double param2)
        {
            double result = param1 + param2;

            IAddHandler handler = OperationContext.Current.GetCallbackChannel<IAddHandler>();
            handler.Resultant(result);
        }
    }
}

Snippet 3 - Configuration

<system.serviceModel>
  <services>
    <service name="DuplexWcfService1.AddService">
      <endpoint address="AddService" binding="wsDualHttpBinding" contract="DuplexWcfService1.IAddService" />
      <host>
        <baseAddresses>
          <add baseAddress="http://localhost:2290/"/>
        </baseAddresses>
      </host>        
    </service>
  </services>
  
  <behaviors>
    <serviceBehaviors>
      <behavior>
        <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
        <serviceMetadata httpGetEnabled="true"/>
        <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
        <serviceDebug includeExceptionDetailInFaults="false"/>
      </behavior>
    </serviceBehaviors>
  </behaviors>
  <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>

I've posted the above sample snippets with namespace for valid reasons. In my configuration I've specified the "name" property of the "service" element as fully qualified name of my service implementation.

If I failed to do so, like if I mentioned "AddService" instead of "DuplexWcfService1.AddService" then, the error "Contract requires Duplex, but Binding 'BasicHttpBinding' doesn't support it or isn't configured properly to support it." will be raised.
Hence be cautious on specifying the values for properties in the configuration.

Now create a console application for consuming the above created service. For that,
  • First add the service reference to the service.
  • Create an implementation for the Callback contract.
  • Call the operation to infer the Duplex MEP.
Snippet 4 - Callback implementation

public class AddHandler : AddServiceServiceReference1.IAddServiceCallback
{

    public void Resultant(double result)
    {
        Console.WriteLine("add result : " + result.ToString());            
    }
}

Snippet 5 - Consuming the service

class Program
{
    static void Main(string[] args)
    {
        InstanceContext instanceContext = new InstanceContext(new AddHandler());
        AddServiceServiceReference1.AddServiceClient serviceClient = new AddServiceServiceReference1.AddServiceClient(instanceContext);

        serviceClient.Add(10, 90);
        Console.ReadKey();
    }
}

In order to understand the implementation easily, I've used primitive data types. Use custom types and scale up the scenario when you try on your own. 

Thursday, May 26, 2011

Silverlight 4 - Bind to a property in the level of parent or Ancestor

In Silverlight, most of us will use the MVVM pattern for which we will create a ViewModel and bind it to the respective View.

In such cases, there might arise a scenario in which we need to bind a property for an element or control which is embeded inside another control. Let us take a real case scenario in order to understand the problem clearer.
Consider that our ViewModel contains two properties (CustomCollection, ButtonVisibility) of which one of type ObservableCollection(CustomCollection) and other one of type Visibility(ButtonVisibility).

Now in the View, first we need to bind the ObservableCollection to a ListBox as follows.

Snippet 1

<Grid x:Name="LayoutRoot" Background="White">
    <ListBox ItemsSource="{Binding Path=CustomCollection}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding Path=CustomName}" />
                    <Button Content="Sample Button"></Button>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>    
</Grid>

Then if i want to set the ButtonVisibility property to the button control inside the DataTemplate of the ListBox, then there should be some way to specify that the property belongs to the ancestor and not the current. Unfortunately we can't directly specify this in Silverlight 4.

In order to achieve this we can do an alternate by using ElementName property of Binding. In MVVM, we will be assigning the ViewModel's instance to the View's DataContext. Hence any root level elemnt can be made use. In our case I'll take the "LayoutRoot" element(which is created by default).

Snippet 2

<Grid x:Name="LayoutRoot" Background="White">
    <ListBox ItemsSource="{Binding Path=CustomCollection}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding Path=CustomName}" />
                    <Button Content="Sample Button" Visibility="{Binding Path=DataContext.ButtonVisibility, ElementName=LayoutRoot}"></Button>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

You can use any valid element name with relevant DataContext you need for the property to bind.

Wednesday, April 27, 2011

Access/Edit files inside Silverlight XAP

While developing Silverlight applications, there were times where we might need to change the contents of a file that resides inside the Silverlight XAP from our ASP.Net hosting application. The ASP.Net (hosting application) holds the XAP file in the ClientBin folder.

One way of editing includes following steps:

  • Since XAP file is nothing but a ZIP file, we need to use any .net library for manipulating zip files. One such library is DotNetZip. Use it to retrieve the contents of XAP file.
  • Access and do related modifications of the file you need to update and save it in the application folder temporarily.
  • Remove the original file from the XAP file.
  • Add the temporary file into the XAP file.
  • Finaly, delete the temporary file.

Consider XAP file consists of xml file of format that we need to update :


<ConfigData>
  <Id>
    InitialTestId1
  </Id>
  <CategoryList>
    <Category ID="01">
      <MainCategory>Category 1</MainCategory>
      <Description>Description 1.</Description>
      <Active>true</Active>
    </Category>
  </CategoryList>
...........................
</ConfigData>


Snippet

In order to change the value of "Id" and remove all "CategoryList" element:
private void EditXAP(string xapFileName, string xmlFileToBeEdited)
{

    string clientBinPath = Server.MapPath(Request.ApplicationPath) + "/ClientBin/";
    string xapFilePath = clientBinPath + xapFileName;
    string templConfigFilePath = clientBinPath + xmlFileToBeEdited;
    Stream configXmlStream = new MemoryStream();
    ZipFile zipFile;

    zipFile = ZipFile.Read(xapFilePath);

    if (zipFile.EntryFileNames.Contains(xmlFileToBeEdited))
    {
        ZipEntry zipEntry = zipFile[xmlFileToBeEdited];
        zipEntry.Extract(configXmlStream);
        configXmlStream.Seek(0, 0);
        XDocument xDocument = XDocument.Load(configXmlStream);

        xDocument.Element("ConfigData").Element("Id").SetValue("AlteredId1");
        xDocument.Element("ConfigData").Elements("CategoryList").Remove();

        xDocument.Save(templConfigFilePath);

        zipFile.RemoveEntry(zipEntry);
        zipFile.AddFile(templConfigFilePath, "");
        zipFile.Save();

        FileInfo tempFile = new FileInfo(templConfigFilePath);
        if (tempFile.Exists)
        {
            tempFile.Delete();
        }
    }
}

Above specified snippet will update the XML file inside the Silvelight XAP.

References
http://dotnetzip.codeplex.com/ 

Tuesday, March 29, 2011

ObservableCollection Filtering

ObservableCollection missed out features
In silverlight projects, we used to work with ObservableCollection for well known reasons. While working so, we can also notice some of the functionalities like AddRange, filtering... missed out, which is required for us at some situations. Similar case arose in my project where I need to provide an observable collection with filtering ability.

Alternate for ObservableCollection filtering
Since we don't have filter option in ObservableCollection, I analysed the effort needed for writing a class which has the basic behaviours of ObservableCollection along with filtering capability. Marc Ridey in his blog have created a FilteredObservableCollection for WPF which I adopted to create one.

Now concentrating on the expected features, we need an object that,
  • holds collection of generic items (T)
  • is able to notify when needed (added, removed, property change notification from the items...)
  • is able to bind with ItemsControl
  • is able to filter.

I decided to just expose the required features. The class should be able to add and remove item(T) even if it doesn't comply with the filtering criteria. But upon iterating, it should expose only the filtered items. If our object is able to notify on collection changed and able to enumerate with filtering ability, then we're 75% nearer to the ObservableCollection with filtering ability.

Find the code below for FilterableNotifiableCollection, that gives the basic features of maintaining a collection and exposes only the filtered items upon iterating it.

Snippet 1
public class FilterableNotifiableCollection<T> : INotifyCollectionChanged, INotifyPropertyChanged, IEnumerable<T>, IEnumerable
{
    #region Class Level Variables

    private ObservableCollection<T> sourceCollection;
    private Predicate<T> currentFilter;

    #endregion

    #region Events

    private event NotifyCollectionChangedEventHandler collectionChanged;
    private event PropertyChangedEventHandler propertyChanged;

    public event NotifyCollectionChangedEventHandler CollectionChanged
    {
        add { collectionChanged += value; }
        remove { collectionChanged -= value; }
    }
    public event PropertyChangedEventHandler PropertyChanged
    {
        add { propertyChanged += value; }
        remove { propertyChanged -= value; }
    }

    #endregion

    #region Properties

    public Predicate<T> Filter
    {
        get { return currentFilter; }
        set
        {
            currentFilter = value;
            this.RefreshCollection();
        }
    }

    public ObservableCollection<T> CoreCollection
    {
        get
        {
            return this.sourceCollection;
        }
    }

    public T this[int index]
    {
        get
        {
            if (this.currentFilter == null)
            {
                return this.sourceCollection[index];
            }
            else
            {
                int currentIndex = 0;
                for (int i = 0; i < this.sourceCollection.Count; i++)
                {
                    T indexitem = this.sourceCollection[i];
                    if (this.currentFilter(indexitem))
                    {
                        if (currentIndex.Equals(index))
                        {
                            return indexitem;
                        }
                        else
                        {
                            currentIndex++;
                        }
                    }
                }
                throw new ArgumentOutOfRangeException();
            }
        }
        set
        {
            if (this.currentFilter == null)
            {
                this.sourceCollection[index] = value;
            }
            else if (!this.currentFilter(value))
            {
                throw new InvalidOperationException("Value doesn't match the filter criteria.");
            }
            else
            {
                bool valueNotSet = true;
                int currentIndex = 0;
                for (int i = 0; i < this.sourceCollection.Count; i++)
                {
                    T indexitem = this.sourceCollection[i];
                    if (this.currentFilter(indexitem))
                    {
                        if (currentIndex.Equals(index))
                        {
                            this.sourceCollection[i] = value;
                            valueNotSet = false;
                            break;
                        }
                        else
                        {
                            currentIndex++;
                        }
                    }
                }

                if (valueNotSet)
                {
                    throw new ArgumentOutOfRangeException();
                }

            }
        }
    }

    #endregion

    #region Constructors

    public FilterableNotifiableCollection(ObservableCollection<T> collectionParam)
    {
        this.sourceCollection = collectionParam;
        currentFilter = null;
        this.sourceCollection.CollectionChanged += new NotifyCollectionChangedEventHandler(SourceCollection_CollectionChanged);
        ((INotifyPropertyChanged)sourceCollection).PropertyChanged += new PropertyChangedEventHandler(SourceCollection_PropertyChanged);
    }

    #endregion

    #region Event Handlers

    void SourceCollection_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (propertyChanged != null)
        {
            propertyChanged(this, e);
        }
    }

    void SourceCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (collectionChanged != null)
        {
            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Add:
                    collectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
                    break;
                case NotifyCollectionChangedAction.Remove:
                    collectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
                    break;
                case NotifyCollectionChangedAction.Replace:
                    collectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
                    break;
                case NotifyCollectionChangedAction.Reset:
                    collectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
                    break;
                default:
                    break;
            }
        }

    }

    #endregion

    #region Public Methods

    public void Add(T item)
    {
        this.sourceCollection.Add(item);
    }

    public void Remove(T item)
    {
        this.sourceCollection.Remove(item);
    }

    public int IndexOf(T item)
    {
        if (currentFilter == null)
            return this.sourceCollection.IndexOf(item);
        else
        {
            int count = 0;
            for (int i = 0; i < this.sourceCollection.Count; i++)
            {
                T indexitem = this.sourceCollection[i];
                if (currentFilter(indexitem))
                {
                    if (indexitem.Equals(item))
                        return count;
                    else
                        count++;
                }
            }
            return -1;
        }
    }

    public void Clear()
    {
        if (currentFilter == null)
        {
            this.sourceCollection.Clear();
        }
        else
        {
            for (int i = 0; i < this.sourceCollection.Count; )
            {
                T item = this.sourceCollection[i];

                if (currentFilter(item))
                {
                    this.sourceCollection.RemoveAt(i);
                }
                else
                {
                    i++;
                }
            }
        }

    }

    public bool Contains(T item)
    {
        if (currentFilter != null && currentFilter(item) == false)
        {
            return false;
        }

        return this.sourceCollection.Contains(item);
    }

    public int Count
    {
        get
        {
            if (currentFilter == null)
            {
                return this.sourceCollection.Count;
            }
            else
            {
                int count = 0;
                for (int i = 0; i < this.sourceCollection.Count; i++)
                {
                    T item = this.sourceCollection[i];

                    if (currentFilter(item))
                    {
                        count++;
                    }
                }

                return count;
            }
        }
    }

    public IEnumerator<T> GetEnumerator()
    {
        return new FilterableEnumerator(this, this.sourceCollection.GetEnumerator());
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return new FilterableEnumerator(this, this.sourceCollection.GetEnumerator());
    }

    public IEnumerable<T> GetFilteredEnumerableGeneric()
    {
        return new FilterableEnumerable(this, this.sourceCollection.GetEnumerator());
    }

    public IEnumerable GetFilteredEnumerable()
    {
        return new FilterableEnumerable(this, this.sourceCollection.GetEnumerator());
    }

    #endregion

    #region Private Methods

    private void RefreshCollection()
    {
        if (collectionChanged != null)
        {
            collectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        }
    }

    #endregion

    #region Inner Classes

    private class FilterableEnumerable : IEnumerable<T>, IEnumerable
    {
        private FilterableNotifiableCollection<T> filterableNotifiableCollection;
        private IEnumerator<T> enumerator;

        public FilterableEnumerable(FilterableNotifiableCollection<T> filterablecollection, IEnumerator<T> enumeratorParam)
        {
            filterableNotifiableCollection = filterablecollection;
            enumerator = enumeratorParam;
        }

        public IEnumerator<T> GetEnumerator()
        {
            return new FilterableEnumerator(filterableNotifiableCollection, enumerator);
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return new FilterableEnumerator(filterableNotifiableCollection, enumerator);
        }
    }

    private class FilterableEnumerator : IEnumerator<T>, IEnumerator
    {
        private FilterableNotifiableCollection<T> filterableObservableCollection;
        private IEnumerator<T> enumerator;

        public FilterableEnumerator(FilterableNotifiableCollection<T> filterablecollection, IEnumerator<T> enumeratorParam)
        {
            filterableObservableCollection = filterablecollection;
            enumerator = enumeratorParam;
        }

        public T Current
        {
            get
            {
                if (filterableObservableCollection.Filter == null)
                    return enumerator.Current;
                else if (filterableObservableCollection.Filter(enumerator.Current) == false)
                    throw new InvalidOperationException();
                else
                    return enumerator.Current;
            }
        }

        public void Dispose()
        {
            enumerator.Dispose();
        }

        object IEnumerator.Current
        {
            get { return this.Current; }
        }

        public bool MoveNext()
        {
            while (true)
            {
                if (enumerator.MoveNext() == false)
                    return false;
                if (filterableObservableCollection.Filter == null
                    || filterableObservableCollection.Filter(enumerator.Current) == true)
                    return true;
            }
        }

        public void Reset()
        {
            enumerator.Reset();
        }
    }

    #endregion

}

The main part I struggled to finalize is the NotifyCollectionChangedAction for which I've used Reset for all the actions. In reference to the msdn article, I took advantage of the following sentence.  You should report Reset in cases where the number of individual Add / Remove / Replace actions necessary to properly report changes in a collection becomes excessive. For example, you should report Reset if a list was completely re-ordered based on some operation such as sorting.
 
This can be further tuned by implementing IList. But in order to make the class simple and just wanted to provide the functionality that we're going to use, I restricted with this. Also I've exposed a property called CoreCollection which returns the original collection, so that if we need the whole collection without filtering, we can make use of that.

Apply Filter
For implementing filter over the FilterableNotifiableCollection, specify a predicate for the Filter property.
 
Snippet 2
private void CheckFilterableNotifiableCollection()
{
    FilterableNotifiableCollection<ContactInfo> contactListTest = new FilterableNotifiableCollection<ContactInfo>(new ObservableCollection<ContactInfo>
    {
        new ContactInfo {ID=111, Email="Balaji@Test.com", Phone="206-555-0108"},
        new ContactInfo {ID=112, Email="Jebarson@Test.com", Phone="206-555-0298"},
        new ContactInfo {ID=113, Email="Jegan@Test.com", Phone="206-555-1130"},
        new ContactInfo {ID=114, Email="RamaPrasad@Test.com", Phone="206-555-0521"}
    }
    );

    contactListTest.Filter = new Predicate<ContactInfo>(FilterByIdGreateThan112);

    listBox.ItemsSource = contactListTest;

}

public bool FilterByIdGreateThan112(ContactInfo contactInfoParam)
{
    if (contactInfoParam.ID > 112)
    {
        return true;
    }
    else
    {
        return false;
    }
}
 
References
http://msdn.microsoft.com/en-us/library/system.collections.specialized.notifycollectionchangedaction(v=vs.95).aspx
http://blog.mridey.com/2009/05/filtered-observablecollection.html
Creative Commons License
This work by Tito is licensed under a Creative Commons Attribution 3.0 Unported License.