Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can use the following class :</p> <pre><code>public class BoundObservableCollection&lt;T, TSource&gt; : ObservableCollection&lt;T&gt; { private ObservableCollection&lt;TSource&gt; _source; private Func&lt;TSource, T&gt; _converter; private Func&lt;T, TSource, bool&gt; _isSameSource; public BoundObservableCollection( ObservableCollection&lt;TSource&gt; source, Func&lt;TSource, T&gt; converter, Func&lt;T, TSource, bool&gt; isSameSource) : base() { _source = source; _converter = converter; _isSameSource = isSameSource; // Copy items AddItems(_source); // Subscribe to the source's CollectionChanged event _source.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_source_CollectionChanged); } private void AddItems(IEnumerable&lt;TSource&gt; items) { foreach (var sourceItem in items) { Add(_converter(sourceItem)); } } void _source_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: AddItems(e.NewItems.Cast&lt;TSource&gt;()); break; case NotifyCollectionChangedAction.Move: // Not sure what to do here... break; case NotifyCollectionChangedAction.Remove: foreach (var sourceItem in e.OldItems.Cast&lt;TSource&gt;()) { var toRemove = this.First(item =&gt; _isSameSource(item, sourceItem)); this.Remove(toRemove); } break; case NotifyCollectionChangedAction.Replace: for (int i = e.NewStartingIndex; i &lt; e.NewItems.Count; i++) { this[i] = _converter((TSource)e.NewItems[i]); } break; case NotifyCollectionChangedAction.Reset: this.Clear(); this.AddItems(_source); break; default: break; } } } </code></pre> <p>Use it as follows :</p> <pre><code>var models = new ObservableCollection&lt;Model&gt;(); var viewModels = new BoundObservableCollection&lt;ViewModel, Model&gt;( models, m =&gt; new ViewModel(m), // creates a ViewModel from a Model (vm, m) =&gt; vm.Model.Equals(m)); // checks if the ViewModel corresponds to the specified model </code></pre> <p>The <code>BoundObservableCollection</code> will be updated when the <code>ObservableCollection</code> will change, but not the other way around (you would have to override a few methods to do that)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload