两个ObservableCollections的双向同步

总览

有时您想在两个方向上同步两个ObservableCollections。
下面的GIF绑定到左侧和ObservableCollection<int>右侧ObservableCollection<string>。这是一个在两个方向上同步两个ObservableCollection的演示,如果您更改一个,则另一个将被反映。

 

Demo

我在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
    {
        /// <summary>
        /// 生成存储从指定的收藏库复制的元素的ObservableCollection
        /// </summary>
        public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> source) => new ObservableCollection<T>(source);

        /// <summary>
        /// 生成指定的ObservableCollection和双向同步的ObservableCollection
        /// </summary>
        public static ObservableCollection<TargetT> ToObservableCollctionSynced<SourceT, TargetT>(this ObservableCollection<SourceT> sources,
        Func<SourceT, TargetT> sourceToTarget, Func<TargetT, SourceT> targetToSource)
        {
            ///sources元素转换后生成收藏
            var targets = sources.Select(sourceToTarget).ToObservableCollection();

            //同步两个收藏集
            SyncCollectionTwoWay(sources, targets, sourceToTarget, targetToSource);

            //返回同步的收藏集
            return targets;
        }

        /// <summary>
        /// 两个ObservableCollection双向同步
        /// </summary>
        public static void SyncCollectionTwoWay<SourceT, TargetT>(ObservableCollection<SourceT> sources, ObservableCollection<TargetT> targets,
            Func<SourceT, TargetT> sourceToTarget, Func<TargetT, SourceT> 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<OriginT, DestT>(ObservableCollection<OriginT> origin, ObservableCollection<DestT> dest,
            Func<OriginT, DestT> 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<int> Sources { get; } = new ObservableCollection<int>(new[] { 10, 20, 30 });
    public ObservableCollection<string> Targets { get; }

    public MainWindowViewModel()
    {

        Targets = Sources
            .ToObservableCollctionSynced(
            x => $"C:{x}",
            x => int.Parse(x.Substring(2)));
    }
}
}

 

在演示中,View是直接更改的,因此我敢在后面的代码中更改它。

 
<Window
   x:Class="ObservableColletionSyncedTest.MainWindow"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   xmlns:local="clr-namespace:ObservableColletionSyncedTest"
   xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   Title="MainWindow"
   mc:Ignorable="d">
   <Window.DataContext>
      <local:MainWindowViewModel />
   </Window.DataContext>
   <UniformGrid Columns="2">
      <StackPanel>
         <Label HorizontalContentAlignment="Center" Content="Source" />
         <Button Click="AddSourceButton_Click" Content="Add" />
         <Button Click="RemoveSourceButton_Click" Content="Remove" />
         <Button Click="ReplaceSourceButton_Click" Content="Replace" />
         <Button Click="MoveSourceButton_Click" Content="Move" />
         <Button Click="ClearSourceButton_Click" Content="Clear" />
         <ListBox x:Name="sources" ItemsSource="{Binding Sources}" />
      </StackPanel>
      <StackPanel>
         <Label HorizontalContentAlignment="Center" Content="Target" />
         <Button Click="AddTargetButton_Click" Content="Add" />
         <Button Click="RemoveTargetButton_Click" Content="Remove" />
         <Button Click="ReplaceTargetButton_Click" Content="Replace" />
         <Button Click="MoveTargetButton_Click" Content="Move" />
         <Button Click="ClearTargetButton_Click" Content="Clear" />
         <ListBox x:Name="targets" ItemsSource="{Binding Targets}" />
      </StackPanel>
   </UniformGrid>
</Window>

 

 
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
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow() { InitializeComponent(); }

        Random random = new Random();
        ObservableCollection<string> targetItems => (targets.ItemsSource as ObservableCollection<string>);
        ObservableCollection<int> sourcesItems => (sources.ItemsSource as ObservableCollection<int>);
        private int CreateSourceValue() => random.Next(0, 99);
        private int GetRandomIndex<T>(Collection<T> 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<T>(ObservableCollection<T> 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值