漫坊亭

社会の底辺プログラマ

Caliburn.Microの小技:NotifyOfPropertyChangeの代わりにSetPropertyを使う

PrismのSetPropertyに慣れていると、Caliburn.Microのプロパティは書くのが面倒くさい。

 
    public int Count
    {
        get { return this._Count; }
        set
        {
            if (this._Count != value)
            {
                this._Count = value;
                this.NotifyOfPropertyChange(() => Count);
            }
        }
    }
    
    private int _Count;

これを、こうしたい。

    public int Count
    {
        get { return this._Count; }
        set { this.SetProperty(ref this._Count, value);
    }
    
    private int _Count;

方法は、プロジェクトに、こんな拡張メソッドを追加する。

// <適当な名前空間・静的クラス名>
    public static bool SetProperty<T>(this PropertyChangedBase vm,
        ref T storage, T value, [CallerMemberName] string propertyName = null)
    {
        var changed = false;
        if (object.Equals(storage, value))
        {
            changed = true;
            storage = value;
            vm.NotifyOfPropertyChange(propertyName);
        }

        return changed;
    }

変更があった時に別の処理(イベントを発生させる、など)は、こう書く。

    set 
    {
        if (this.SetProperty(ref this._Count, value))
        {
            this.NotifyOfPropertyChange(()=>xxx);
        }
    }