SourceChord

C#とXAML好きなプログラマの備忘録。最近はWPF系の話題が中心です。

Prism.Mvvmを使ってみる

Prism 5.0では、各機能ごとにパッケージが細かく分けられています。
今回は、MVVM系の機能がまとめられた、Prism.Mvvmだけの部分を使用してみたいと思います。

https://pnpmvvm.codeplex.com/


Prism.Mvvmに用意されてるのは、以下のような機能です。

クラス 内容
DelegateCommand VMの任意のメソッドを呼び出すためのICommand実装クラス
CompositeCommand 複数のコマンドをまとめて実行するためのクラス
BindableBase INotifyPropertyChangedの実装お助けクラス
ErrorsContainer INotifyDataErrorInfoの実装お助けクラス
PropertySupport プロパティ名の文字列を取得するためのヘルパークラス
ViewModelLocationProvider ViewとViewModelを結び付けるためのクラス


まずは、使い方も簡単で頻繁に使いそうなクラスのDelegateCommandとBindableBaseを使ってみます。

準備

  1. 新規プロジェクトで「WPFアプリケーション」プロジェクトを作成
  2. NugetでPrism.Mvvmをインポート

f:id:minami_SC:20140508003949p:plain:w300
f:id:minami_SC:20140508003959p:plain:w300

これでPrism.Mvvmを使う準備は完了。


使ってみる

とりあえず、以下のようなサンプルプログラムを作ってみたいと思います。
f:id:minami_SC:20140508004055p:plain:w200

  1. TextBoxに入力した文字列は、VMのNameプロパティにバインド
  2. ButtonをクリックするとShowMessageCommandを実行
    1. このコマンドが実行されて、入力された文字列を加工して、TextBlockに結果を表示

ViewModelの作成

以下のようなファイル名でVMを作成します。

MainWindowViewModel.cs
  1. 以下二つの名前空間のusing文を追加
    1. using Microsoft.Practices.Prism.Mvvm;
    2. using Microsoft.Practices.Prism.Commands;
  2. VMをBindableBaseから派生させて、INotifyPropertyChangedの更新通知を簡単に実装できるようにする
  3. Buttonを押したときに実行する処理は、DelegateCommandを使って実装
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.Prism.Mvvm;
using Microsoft.Practices.Prism.Commands;
namespace PrismTest
{
    class MainWindowViewModel : BindableBase
    {
        private string name;
        public string Name
        {
            get { return name; }
            set { this.SetProperty(ref this.name, value); }
        }

        private string message;
        public string Message
        {
            get { return message; }
            set { this.SetProperty(ref this.message, value); }
        }

        private DelegateCommand showMessageCommand;
        public DelegateCommand ShowMessageCommand
        {
            get { return showMessageCommand = showMessageCommand ?? new DelegateCommand(ShowMessage); }
        }

        private void ShowMessage()
        {
            this.Message = string.Format("こんにちは、 {0} さん", this.Name);
        }
    }
}

Viewの作成

MainWindow.xaml
<Window x:Class="PrismTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Width="300"
        Height="200">
    <StackPanel>
        <TextBlock Margin="20,10"
                   HorizontalAlignment="Left"
                   Text="{Binding Message}"
                   TextWrapping="Wrap" />
        <TextBox Width="120"
                 Height="23"
                 Margin="20,10"
                 HorizontalAlignment="Left"
                 Text="{Binding Name}"
                 TextWrapping="Wrap" />
        <Button Width="75"
                Margin="20,10"
                HorizontalAlignment="Left"
                Command="{Binding ShowMessageCommand}"
                Content="Button" />
    </StackPanel>
</Window>
MainWindow.xaml.cs

コードビハインドでは、VMをDataContextにセットするだけ。

    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainWindowViewModel();
        }
    }

うん、これは便利!!


今まで、自分でBindableBaseとかRelayCommandクラスを作って、↓に書いたみたいにプロジェクトテンプレート作ったりしてたけど、、、
VSのプロジェクト・テンプレートを作成する - SourceChord
わざわざ車輪の再発明するより、こういう標準的なライブラリを使った方がよさげですね。
一度、自分で車輪を作ってみるのも、いい勉強にはなったけど。


Prism.Mvvmで用意されてる、他のクラスについてはまた次回に続きます。