有时您想在两个方向上同步两个ObservableCollections。 下面的GIF绑定到左侧和ObservableCollection
右侧ObservableCollection
。这是一个在两个方向上同步两个ObservableCollection的演示,如果您更改一个,则另一个将被反映。
我在WPF中创建了演示,但是ObservableCollection本身不依赖于WPF,因此可以在UWP和控制台中使用。
代码我要CollectionChanged
订阅两个事件,然后更改另一端以同步两个ObservableCollections 。 为了避免无限循环,局部变量isChanging
保持已存在或正在更改的状态。
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
namespace ObservableColletionSyncedTest
{
public static class ObservableCollectionExtension
{
///
/// 生成存储从指定的收藏库复制的元素的ObservableCollection
///
public static ObservableCollection ToObservableCollection(this IEnumerable source) => new ObservableCollection(source);
///
/// 生成指定的ObservableCollection和双向同步的ObservableCollection
///
public static ObservableCollection ToObservableCollctionSynced(this ObservableCollection sources,
Func sourceToTarget, Func targetToSource)
{
///sources元素转换后生成收藏
var targets = sources.Select(sourceToTarget).ToObservableCollection();
//同步两个收藏集
SyncCollectionTwoWay(sources, targets, sourceToTarget, targetToSource);
//返回同步的收藏集
return targets;
}
///
/// 两个ObservableCollection双向同步
///
public static void SyncCollectionTwoWay(ObservableCollection sources, ObservableCollection targets,
Func sourceToTarget, Func targetToSource)
{
bool isChanging = false;
//Source -> Target
sources.CollectionChanged += (o, e) =>
ExcuteIfNotChanging(() => SyncByChangedEventArgs(sources, targets, sourceToTarget, e));
//Target -> Source
targets.CollectionChanged += (o, e) =>
ExcuteIfNotChanging(() => SyncByChangedEventArgs(targets, sources, targetToSource, e));
//为了不发生变更,用本地变量检查
//为了访问本地变量,用本地函数描述
void ExcuteIfNotChanging(Action action)
{
if (isChanging)
return;
isChanging = true;
action.Invoke();
isChanging = false;
}
}
private static void SyncByChangedEventArgs(ObservableCollection origin, ObservableCollection dest,
Func originToDest, NotifyCollectionChangedEventArgs originE)
{
switch (originE.Action)
{
case NotifyCollectionChangedAction.Add:
if (originE.NewItems?[0] is OriginT addItem)
dest.Insert(originE.NewStartingIndex, originToDest(addItem));
return;
case NotifyCollectionChangedAction.Remove:
if (originE.OldStartingIndex >= 0)
dest.RemoveAt(originE.OldStartingIndex);
return;
case NotifyCollectionChangedAction.Replace:
if (originE.NewItems?[0] is OriginT replaceItem)
dest[originE.NewStartingIndex] = originToDest(replaceItem);
return;
case NotifyCollectionChangedAction.Move:
dest.Move(originE.OldStartingIndex, originE.NewStartingIndex);
return;
case NotifyCollectionChangedAction.Reset:
dest.Clear();
foreach (DestT item in origin.Select(originToDest))
dest.Add(item);
return;
}
}
}
}
用法很简单,只需使用原始ObservableCollection中的扩展方法调用即可。那时,将双向元素转换的委托指定为参数。 在此,Source-> Target是转换为字符串的数字,并添加了固定字符串,Target-> Source是从第三个字符转换为数字的字符串。
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
namespace ObservableColletionSyncedTest
{
class MainWindowViewModel
{
public ObservableCollection Sources { get; } = new ObservableCollection(new[] { 10, 20, 30 });
public ObservableCollection Targets { get; }
public MainWindowViewModel()
{
Targets = Sources
.ToObservableCollctionSynced(
x => $"C:{x}",
x => int.Parse(x.Substring(2)));
}
}
}
在演示中,View是直接更改的,因此我敢在后面的代码中更改它。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ObservableColletionSyncedTest
{
///
/// Interaction logic for MainWindow.xaml
///
public partial class MainWindow : Window
{
public MainWindow() { InitializeComponent(); }
Random random = new Random();
ObservableCollection targetItems => (targets.ItemsSource as ObservableCollection);
ObservableCollection sourcesItems => (sources.ItemsSource as ObservableCollection);
private int CreateSourceValue() => random.Next(0, 99);
private int GetRandomIndex(Collection collection) => random.Next(0, collection.Count);
private void AddSourceButton_Click(object sender, RoutedEventArgs e) =>
sourcesItems.Add(CreateSourceValue());
private void AddTargetButton_Click(object sender, RoutedEventArgs e) =>
targetItems.Add($"A:{CreateSourceValue()}");
private void RemoveSourceButton_Click(object sender, RoutedEventArgs e) =>
sourcesItems.RemoveAt(GetRandomIndex(sourcesItems));
private void RemoveTargetButton_Click(object sender, RoutedEventArgs e) =>
targetItems.RemoveAt(GetRandomIndex(targetItems));
private void ReplaceSourceButton_Click(object sender, RoutedEventArgs e) =>
sourcesItems[GetRandomIndex(sourcesItems)] = CreateSourceValue();
private void ReplaceTargetButton_Click(object sender, RoutedEventArgs e) =>
targetItems[GetRandomIndex(targetItems)] = $"R:{CreateSourceValue()}";
private void Move(ObservableCollection collection)
{
int indexOld = GetRandomIndex(collection);
int indexNew = GetRandomIndex(collection);
collection.Move(indexOld, indexNew);
}
private void MoveSourceButton_Click(object sender, RoutedEventArgs e) => Move(sourcesItems);
private void MoveTargetButton_Click(object sender, RoutedEventArgs e) => Move(targetItems);
private void ClearSourceButton_Click(object sender, RoutedEventArgs e) => sourcesItems.Clear();
private void ClearTargetButton_Click(object sender, RoutedEventArgs e) => targetItems.Clear();
}
}
在演示中,为了清楚起见,两个ObservableCollections都绑定到了View,但是为此目的,最好将双向转换Converter放在任一ListBox中。 实际上,我认为有很多用途,例如想要同步Model层和ViewModel层的ObservableCollection。
无法取消订阅ColletionChanged事件,因此,如果两个ObservableCollection具有不同的生存期,则它们将泄漏内存。
参考http://nomoredeathmarch.hatenablog.com/entry/2019/03/02/180147
整个代码将其放置在以下位置。https://github.com/soi013/ObservableColletionSyncedTest/
环境VisualStudio 2019版本16.8.3 .NET Core 3.1 C#8