ObservableCollection Selector

Collection: SelectObservatorCollection<TSource, T>
Extension method: ObservatorCollectionExtensions.Select(source, selector)

Description

This collection listens to an IObservableCollection to build new items based on the original items. This is especially useful when dealing with multiple layers where each layer has to observe the previous one.

Example

The following example shows how to create a collection of ViewModels listening to a collection of Models. First of all, we need to make the model and viewModel entities.

using System.ComponentModel;
using ZumtenSoft.WpfUtils.Collections;

public class ModelItem : INotifyPropertyChanged
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            if (_name != value)
            {
                _name = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("Name"));
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

public class ViewModelItem : INotifyPropertyChanged
{
    public ModelItem Source { get; private set; }

    public ViewModelItem(ModelItem source)
    {
        Source = source;
        Source.PropertyChanged += SourceOnPropertyChanged;
    }

    private void SourceOnPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        switch (e.PropertyName)
        {
            case "Name":
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("Name"));
                break;
        }
    }

    public string Name
    {
        get { return Source.Name; }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

Once this is completed, simply use the ObservableCollection Linq Selector like this:

IObservableCollection<ModelItem> models = new ObservableCollection<ModelItem>();

// Either use the Method Chain syntax
IObservableCollection<ViewModelItem> viewModels =
    models.Select(model => new ViewModelItem(model));

// Or the SQL-like syntax
IObservableCollection<ViewModelItem> viewModels =
    from model in models
    select new ViewModelItem(model);

Last edited May 19, 2013 at 11:41 PM by Zumten, version 4

Comments

No comments yet.