views:

1944

answers:

2

I have an ObservableCollection feeding a DataGrid thats updating nicely.

The point: I want to filter (collapse) the rows without removing them from the collection.

Is there a way to do this, or place a view on the Grid like normal .Net?

+1  A: 

I've just published a post on my blog that addresses this exact issue.

Attached to the post is a simple demo application that demonstrates how to achieve what you want.

The solution should be general enough to be reusable and is based around the following custom extension method:

public static class Extensions
{
    /// <summary>
    /// Applies an action to each item in the sequence, which action depends on the evaluation of the predicate.
    /// </summary>
    /// <typeparam name="TSource">The type of the elements of source.</typeparam>
    /// <param name="source">A sequence to filter.</param>
    /// <param name="predicate">A function to test each element for a condition.</param>
    /// <param name="posAction">An action used to mutate elements that match the predicate's condition.</param>
    /// <param name="negAction">An action used to mutate elements that do not match the predicate's condition.</param>
    /// <returns>The elements in the sequence that matched the predicate's condition and were transformed by posAction.</returns>
    public static IEnumerable<TSource> ApplyMutateFilter<TSource>(this IEnumerable<TSource> source,
                                                                  Func<TSource, bool> predicate,
                                                                  Action<TSource> posAction,
                                                                  Action<TSource> negAction)
    {
        if (source != null)
        {
            foreach (TSource item in source)
            {
                if (predicate(item))
                {
                    posAction(item);
                }
                else
                {
                    negAction(item);
                }
            }
        }

        return source.Where(predicate);
    }
}
Peter McGrattan
A: 

If you have a view on top of your observable collection you can achieve that. I have written an article on filtering the Silverlight datagrid. you have there a FilteredCollectionView on which you can add any IFilter. Here is the link to the article:

http://www.codeproject.com/KB/silverlight/autofiltering_silverlight.aspx

Hope it helps you.