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



我有一个可观察的集合,在那里我添加了我的项目,并与xaml中的"Listbox"绑定。但我想维护这个可观察集合的克隆,并将该克隆可观察集合绑定到"Listbox"中,而不是原始的可观察集合,然后首先将项目添加到该克隆可观测集合中,然后单击按钮更新原始可观察集合。我正在按应用程序使用MVVM Light。

有什么帮助吗。?这是我最初可观察到的收藏品。

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

我还没有测试过这段代码,但它应该可以正常工作。我已经在克隆上连接了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);
        }
    }
}
}

最新更新