如何在WPF中维护两个具有相同项目的可观察集合?

时间:2015-04-08 05:12:43

标签: c# wpf xaml mvvm observablecollection

我有这个可观察的集合,我在其中添加我的项目并与xaml中的“Listbox”绑定。但我想维护这个可观察集合的克隆,并将该克隆可观察集合绑定到“Listbox”而不是原始Observable Collection,并首先将项添加到该克隆的observable集合中,并通过单击按钮更新Original Observable Collection。我正在使用MVVM Light作为应用程序。

对此有任何帮助。?这是我最初的可观察系列。

public ObservableCollection<ColumnNameDefinition> HistoricColumns { get; set; }

1 个答案:

答案 0 :(得分:2)

我没有测试过这段代码,但它应该可以正常工作。我已经在克隆上连接了CollectionChanged事件,我正在维护一系列更改。然后,如果要提交更改,只需执行CommitChangesCommand,所有更改都将添加到源中。

using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Windows.Input;

namespace WpfApplication1
{
public class ViewModel
{
    private readonly ObservableCollection<Item> _clone;

    private readonly ObservableCollection<Item> _source;

    private readonly Collection<Item> _changes = new Collection<Item>();

    public ViewModel(ObservableCollection<Item> items)
    {
        _source = items;            
        _clone = new ObservableCollection<Item>(items);
        _clone.CollectionChanged += clone_CollectionChanged;
    }

    void clone_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        switch (e.Action)
        {
            case NotifyCollectionChangedAction.Add:
                foreach (var newItem in e.NewItems.Cast<Item>())
                {
                    _changes.Add(newItem);
                }
                break;
        }
    }

    public ObservableCollection<Item> Clone
    {
        get { return _clone; }
    }

    private DelegateCommand _commitChangesCommand;

    public ICommand CommitChangesCommand
    {
        get { return _commitChangesCommand ?? (_commitChangesCommand = new DelegateCommand(CommitChanges, CanCommitChanges)); }
    }

    private void CommitChanges(object sender)
    {
        foreach (var change in _changes)
        {
            _source.Add(change);
        }

        _changes.Clear();
    }

    private bool CanCommitChanges(object sender)
    {
        return _changes.Any();
    }
}

public class Item
{
}

public class DelegateCommand : ICommand
{
    private readonly Predicate<object> _canExecute;
    private readonly Action<object> _execute;

    public event EventHandler CanExecuteChanged;

    public DelegateCommand(Action<object> execute)
        : this(execute, null)
    {
    }

    public DelegateCommand(Action<object> execute,
        Predicate<object> canExecute)
    {
        _execute = execute;
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter)
    {
        return _canExecute == null || _canExecute(parameter);
    }

    public void Execute(object parameter)
    {
        _execute(parameter);
    }

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