RunningCSharp

MS系開発者による、雑多な記事。記事は所属企業とは関係のない、個人の見解です。

C#+XAML:MVVM Light Toolkitのスニペット導入方法など

スニペットのDLと配置(Visual Studio 2015の場合)

1:http://mvvmlight.codeplex.com/sourcecontrol/latestの「Download」リンクから、圧縮された全ソースコードをダウンロード

2:ファイルを解凍し、\Installer\InstallItems\Snippets\CSharp にスニペットがあるのですべてコピー

3:%UserProfile%\Documents\Visual Studio 2015\Code Snippets\Visual C#\My Code Snippets にすべて貼り付け

・(個人的に)よく使うスニペット紹介

「mvvminpc」

プロパティ変更通知メソッド呼び出しが付いたプロパティのスニペット。 下記のようなプロパティ宣言が展開され、プロパティ名(MyPropertyとなっている所)を書き換えると文字リテラルのプロパティ名も連動して書き換えられます。

/// <summary>
/// The <see cref="MyProperty" /> property's name.
/// </summary>
public const string MyPropertyPropertyName = "MyProperty";

private bool _myProperty = false;

/// <summary>
/// Sets and gets the MyProperty property.
/// Changes to that property's value raise the PropertyChanged event. 
/// </summary>
public bool MyProperty
{
    get
    {
        return _myProperty;
    }

    set
    {
        if (_myProperty == value)
        {
            return;
        }

        _myProperty = value;
        RaisePropertyChanged(MyPropertyPropertyName);
    }
}

「mvvmrelay」

コマンドプロパティ用のスニペットスニペットが用意したラムダ式を埋めるだけで操作記述が完結するのがうれしいです。

private RelayCommand _myCommand;

/// <summary>
/// Gets the MyCommand.
/// </summary>
public RelayCommand MyCommand
{
    get
    {
        return _myCommand
            ?? (_myCommand = new RelayCommand(
            () =>
            {

            }));
    }
}

「mvvmrelaygeneric」

上記コマンドプロパティのジェネリック版。 コマンドパラメータを指定するときはこちらを利用。

private RelayCommand<string> _myCommand;

/// <summary>
/// Gets the MyCommand.
/// </summary>
public RelayCommand<string> MyCommand
{
    get
    {
        return _myCommand
            ?? (_myCommand = new RelayCommand<string>(
            p =>
            {

            }));
    }
}

・おまけ(多用はしていない)

「mvvminpclambda」

文字列ではなく、ラムダ式でプロパティそのものを返却することで呼び出し先で式木からプロパティ名を取得している。 スニペット中には使用されない文字列型の宣言が残ったままです。

/// <summary>
/// The <see cref="MyProperty" /> property's name.
/// </summary>
public const string MyPropertyPropertyName = "MyProperty";

private bool _myProperty = false;

/// <summary>
/// Sets and gets the MyProperty property.
/// Changes to that property's value raise the PropertyChanged event. 
/// </summary>
public bool MyProperty
{
    get
    {
        return _myProperty;
    }

    set
    {
        if (_myProperty == value)
        {
            return;
        }

        _myProperty = value;
        RaisePropertyChanged(() => MyProperty);
    }
}

「mvvminpc」、「mvvminpclambda」ともに.netFramework4.5からはnameof演算子があるため、文字列やラムダ式でプロパティ名を渡さなくてよい(MVVMLignt ToolkitのViewModelBaseにもプロパティ名などの引数を受け取らないRaisePropertyChangedのオーバーライドも用意されている)ため、.netFramework4.5(C#5)向けのもう少しすっきりしたスニペットを自作したほうがよいかな、と記事を書きながら思いました。