フォーラムの質問にReactivePropertyサンプルで答える

id:neueccさんが作ったReactivePropertyというライブラリが素敵すぎて悶え死にそうな今日この頃、
たまたまMSDNフォーラムでReactiveProperty使えそうな質問があったのでサンプル作ってみた。

MSDNフォーラムの記事↓
■CheckBox付きのListBoxでチェックの付いている項目だけを別のListBoxに表示するには?
http://social.msdn.microsoft.com/Forums/ja-JP/wpfja/thread/ead88361-cca8-4bc9-b495-a7822d851de9

2つのListBoxを連動させたいってもの。

↓作ったサンプルはこれ↓
https://skydrive.live.com/?cid=bc790e45968a1da9&sc=documents&uc=1&id=BC790E45968A1DA9%21109#

やっぱり、ReactivePropertyの何が凄いって、Property毎にObserve(観察)できるとこ(他にも沢山あるけど)

ちなみに書いたソースはこんだけ

    class MainViewModel
    {
        public ReactiveCollection<Item> Items1 { get; private set; }
        public ReactiveCollection<Item> Items2 { get; private set; }
        public ReactiveProperty<bool> IsVisible { get; private set; }

        public MainViewModel()
        {
            var aaa = new Item("aaa");
            var bbb = new Item("bbb");
            var ccc = new Item("ccc");

            Items1 = new Item[] { aaa, bbb, ccc }.ToObservable().ToReactiveCollection();
            Items2 = new ReactiveCollection<Item>();

            //aaa.IsChecked.ObserveProperty(x => x.Value).Where(x => x).Subscribe(x => Items2.Add(aaa));
            //aaa.IsChecked.ObserveProperty(x => x.Value).Where(x => !x).Subscribe(x => Items2.Remove(aaa));

            //bbb.IsChecked.ObserveProperty(x => x.Value).Where(x => x).Subscribe(x => Items2.Add(bbb));
            //bbb.IsChecked.ObserveProperty(x => x.Value).Where(x => !x).Subscribe(x => Items2.Remove(bbb));

            //ccc.IsChecked.ObserveProperty(x => x.Value).Where(x => x).Subscribe(x => Items2.Add(ccc));
            //ccc.IsChecked.ObserveProperty(x => x.Value).Where(x => !x).Subscribe(x => Items2.Remove(ccc));

            /* 2011.10.21 */
            /* neueさんのご指摘で気づきました、「ObserveProperty」は不要でしたので修正します。 */

            aaa.IsChecked.Where(x => x).Subscribe(x => Items2.Add(aaa));
            aaa.IsChecked.Where(x => !x).Subscribe(x => Items2.Remove(aaa));

            bbb.IsChecked.Where(x => x).Subscribe(x => Items2.Add(bbb));
            bbb.IsChecked.Where(x => !x).Subscribe(x => Items2.Remove(bbb));

            ccc.IsChecked.Where(x => x).Subscribe(x => Items2.Add(ccc));
            ccc.IsChecked.Where(x => !x).Subscribe(x => Items2.Remove(ccc));

            IsVisible = new ReactiveProperty<bool>();

            var cmd = Items2.CollectionChangedAsObservable().Subscribe(_ => IsVisible.Value = Items2.Count > 0);
        }
    }

    class Item
    {
        public ReactiveProperty<bool> IsChecked { get; private set; }

        public ReactiveProperty<string> Text { get; private set; }

        public Item(string text)
        {
            IsChecked = new ReactiveProperty<bool>();
            Text = new ReactiveProperty<string>(text);
        }
    }

こんくらいのサンプルだとPrismもINotifyPropertyChangedもいらない。
RaisePropertyChangedもいらない。
PropertyChangedEventArgsとってプロパティ名調べてなんてこともいらない。

MVVMもこんなに簡単。
そう、ReactivePropertyならね!