WPF > 実装: ObservableCollection<T>型のSingleton の使用 > データ追加 + DataGridへのbinding


動作環境
Windows 8.1 Pro (64bit)
Microsoft Visual Studio 2017 Community

背景

MVVMにおいて、複数のVMがあるとする。それらにおいて、あるデータの同期をとってほしい。つまり、一つのVMにおいてデータが更新された時、別のVMにおいてその更新が反映されて欲しい。

最初考えたのはVM同士のやりとりだったが、以下を見つけた。

MVVMにおいてはViewModel同士がお互いを操作する必要なんて基本的にはありません。所有関係はあることはありますがそもそもViewModelはModelの影なのです。そしてまたViewはViewModelの影でもあります。

では、このような場合、シングルトンを使うことになるのだろうか。

MVVMでModelを複数のViewModelから利用する

参考

参考: Unity C# シングルトンパターンの実装
情報ありがとうございます。

上記の実装に関して、自分が使いたいObservableCollection<TestItem>に対応した。

ファイル構成

  • VideModelBase.cs
  • ViewModel.cs
  • SampleSingleton.cs : シングルトン用
  • TestItem.cs : TestItem項目の定義
  • MainWindow.xaml : デザイン
  • MainWindow.xaml.cs : コードビハインド

実装

ViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//
using System.Collections.ObjectModel;

namespace _170702_t1115_singleton_ObsCol
{
    class ViewModel : ViewModelBase
    {
        // コンストラクタ
        public ViewModel()
        {
            myItem = SampleSingleton.Instance;
            myItem.Add(new TestItem { Id = 0, Name = "7of9", Age = 30, Gender = "Female" });

            var data2 = SampleSingleton.Instance;
            data2.Add(new TestItem { Id = 1, Name = "Janeway", Age = 50, Gender = "Female" });
        }

        public ObservableCollection<TestItem> myItem { get; set; }
    }
}
SampleSingleton.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//
using System.Collections.ObjectModel;

namespace _170702_t1115_singleton_ObsCol
{
    class SampleSingleton
    {
        private static ObservableCollection<TestItem> instance;

        private SampleSingleton()
        {
        }

        public static ObservableCollection<TestItem> Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new ObservableCollection<TestItem>();
                }
                return instance;
            }
        }
    }
}
TestItem.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _170702_t1115_singleton_ObsCol
{
    class TestItem
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Gender { get; set; }
    }
}
MainWindow.xaml
<Window x:Class="_170702_t1115_singleton_ObsCol.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:_170702_t1115_singleton_ObsCol"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:ViewModel/>
    </Window.DataContext>
    <Grid>
        <DataGrid x:Name="dataGrid1" ItemsSource="{Binding myItem}"/>
    </Grid>
</Window>
MainWindow.xaml.cs
using System;
using System.Collections.Generic;
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 _170702_t1115_singleton_ObsCol
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

実行

data1とdata2で追加した項目が両方表示されている。
Singletonとして機能していることが見られる。