Silverlight Prism フレームワークを利用してMVVMアプリケーションを作成してみる 第2回 MVVMパターンの作成

MVVM QuickStart を参考にしつつ、アプリケーションに、Prism フレームワークを適用させていく。

Silverlight Prism フレームワークを利用してMVVMアプリケーションを作成してみる 第1回 で、モジュールの分割と、UI合成の動作を確認するところまでできたので、今回は、MVVMパターンと各クラスの責務を再確認したのち、データの参照をするところまでを実装してみる。

クラスの責任と特徴

Model-View-ViewModel(MVVM) パターンは、ビジネスおよびプレゼンテーションロジックをユーザーインターフェースから明確に分離する助けになる。

MVVMパターンでは、3つのクラスに責務を分離する。

  • View : UIおよびUIロジックをカプセル化
  • View Model : プレゼンテーションロジックと状態をカプセル化
  • Model : ビジネスロジックとデータをカプセル化

View は View Model と データバインディング、コマンド、通知イベントを通して影響し合う。View Modelは、問い合わせ、監視し、調整、更新をモデルに行う。変換、妥当性検査、データの凝集は必要に応じ、Viewで行う。

MVVM クラスと相互作用

prism_handson12

View クラス

Viewの責務は、ユーザーへスクリーン上の構造と見え方を定義すること。理想的には、コードビハインドでは、コンストラクタでInitializeComponent メソッドのみを呼び出すようにする。いくつかの場合、コードビハインドは、XAMLでは表現が困難な振る舞いをUIロジックとして含む。

Viewのデータバインディング式は、データコンテキストについて評価される。MVVMでは、Viewのデータコンテキストには、View Modelが設定される。View Model は、Viewがバインドや通知できるプロパティとコマンドが実装される。通常、一対一の関連がViewとView Modelに設定される。

通常、View は、Control もしくは UserControl の派生クラス。しかしながら、いくつかの場合、View は、データテンプレートとして表現される。

View Model クラス

MVVMにて、View Model は、Viewのためのプレゼンテーションロジックおよびデータをカプセル化する。View Model は、直接 Viewへの参照は持たないし、View の実装や型についても何も知らない。View Model は、プロパティやコマンドを、Viewとのデータバインドやイベントを通じた状態の変更通知を可能にするために実装する。

View Model は、View と Model との相互作用の調整に責任を持つ。一般的にこれは、一対多の関係となる。

Model クラス

MVVMにて、Model は、ビジネスロジックとデータをカプセル化する。通常、Modelは、アプリケーションのクライアント側ドメインモデルを表現する。Model は、データアクセスとキャッシングのサポートコードを含む。

通常、Model は、View とのバインドが容易になる機能を実装する。これは、通常、プロパティやコレクションの変更が、INotifyPropertyChanged、INotifyCollectionChanged インターフェースを通して通知されることを意味する。Model クラスは、オブジェクトのコレクションを、ObservableCollection<T> で表現する。これは、INotifyCollectionChanged インターフェースを実装している。

Model は、データの妥当性検査やエラー報告を、IDataErrorInfo( もしくは INotifyDataErrorInfo) インターフェースでサポートする。

Model-View-ViewModel の作成

と、MVVMにおける、各クラスの責務を概観したところで、今回、プロジェクト工数見積のクライアントをSilverlightで作成することを題材としている、対象「プロジェクト」の部分を参照する部分を実装していきたいと思う。

題材は、システム開発工数をファンクションポイント法 を使って見積もるというもので、GAEを利用して作ってある

prism_handson13

Model の作成

まずは、工数算出対象である、Project モデルを作成。

  1. namespace ProjectModule.Models
  2. {
  3. public class Project
  4. {
  5. public string Key { get; set; }
  6. public string Owner { get; set; }
  7. public string SystemName { get; set; }
  8. public string ApplicationName { get; set; }
  9. public string MesurementType { get; set; }
  10. }
  11. }

そして、Project のコレクションを表現するために、Projecs クラスを作成する。

  1. using System.Collections.ObjectModel;
  2.  
  3. namespace ProjectModule.Models
  4. {
  5. public class Projects : ObservableCollection
  6. {
  7. }
  8. }

データサービスの作成

Project データを取得するデータサービスを作成。現時点では、ダミーデータを返すようにしておく。

インターフェース

  1. using ProjectModule.Models;
  2.  
  3. namespace ProjectModule.Services
  4. {
  5. public interface IProjectDataService
  6. {
  7. Projects GetProjects();
  8. }
  9. }

ダミーデータを返す実装

DIコンテナに認識させるために、Export アトリビュートを設定しておく。ここでは、まだ、ダミーデータを返すようにしておく。Webサービスとの連携は別途実装する。

  1. using System.ComponentModel.Composition;
  2. using ProjectModule.Models;
  3.  
  4. namespace ProjectModule.Services
  5. {
  6. [Export(typeof(IProjectDataService))]
  7. public class ProjectDataService : IProjectDataService
  8. {
  9. private Projects projects;
  10.  
  11. public Projects GetProjects()
  12. {
  13. if (this.projects == null)
  14. {
  15. this.projects = new Projects {
  16. new Project(){
  17. Key = "001",
  18. SystemName = "Sys1",
  19. ApplicationName="Test App1"
  20. },
  21. :
  22. };
  23. }
  24. return this.projects;
  25. }
  26.  
  27. }
  28. }

ViewModelの作成

INotifyChanged を実装し、ImportingConstructor アトリビュートを指定することで、コンストラクタインジェクションを行い、上記で作成した、データサービスをインジェクションする。

また、ViewModel 自体も、View にインジェクションするために、Export アトリビュートを付与し、DIコンテナに登録されるようにしておく。

  1. using System;
  2. using System.ComponentModel;
  3. using System.ComponentModel.Composition;
  4. using System.Windows.Data;
  5. using Microsoft.Practices.Prism.Events;
  6. using ProjectModule.Events;
  7. using ProjectModule.Models;
  8. using ProjectModule.Services;
  9.  
  10. namespace ProjectModule.ViewModels
  11. {
  12. [Export]
  13. public class ProjectListViewModel : INotifyPropertyChanged
  14. {
  15. private readonly IEventAggregator eventAggregator;
  16. public ICollectionView Projects { get; private set; }
  17.  
  18. [ImportingConstructor]
  19. public ProjectListViewModel(IProjectDataService dataService, IEventAggregator eventAggregator)
  20. {
  21. if (dataService == null) throw new ArgumentNullException("dataService");
  22. if (eventAggregator == null) throw new ArgumentNullException("eventAggregator");
  23.  
  24. this.eventAggregator = eventAggregator;
  25.  
  26. this.Projects = new PagedCollectionView(dataService.GetProjects());
  27. this.Projects.CurrentChanged += new EventHandler(this.SelectedProjectChanged);
  28. }
  29.  
  30.  
  31. private void SelectedProjectChanged(object sender, EventArgs e)
  32. {
  33. Project project = this.Projects.CurrentItem as Project;
  34. if (project != null)
  35. {
  36. this.eventAggregator.GetEvent<ProjectSelectedEvent>().Publish(project.Key);
  37. }
  38. }
  39. #region INotifyPropertyChanged Members
  40.  
  41. public event PropertyChangedEventHandler PropertyChanged;
  42.  
  43. private void NotifyPropertyChanged(string propertyName)
  44. {
  45. if (this.PropertyChanged != null)
  46. {
  47. this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
  48. }
  49. }
  50. #endregion
  51.  
  52. }
  53. }

Viewの作成

前回 Hello Word としていた、ProjectList を ProjectListView に リネームして、コントロールを配置。

データバインドを利用して、Project クラス のプロパティとバインドする。

prism_handson14

  1. <UserControl x:Class="ProjectModule.Views.ProjectListView"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:Controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
  5. xmlns:prism="http://www.codeplex.com/prism">
  6. <Grid x:Name="LayoutRoot" Background="White">
  7. <Grid.ColumnDefinitions>
  8. <ColumnDefinition Width="*" />
  9. <ColumnDefinition Width="*" />
  10. </Grid.ColumnDefinitions>
  11. <Grid.RowDefinitions>
  12. <RowDefinition Height="Auto" />
  13. <RowDefinition Height="*" />
  14. <RowDefinition Height="Auto" />
  15. </Grid.RowDefinitions>
  16.  
  17. <TextBlock Grid.Row="0" Text="Projects List View" TextWrapping="Wrap" Grid.RowSpan="1" Grid.ColumnSpan="2" FontSize="18" Foreground="#FF2F3806" Margin="8,8,8,8" />
  18.  
  19. <Controls:DataGrid x:Name="ProjectsList" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" SelectionMode="Single"
  20. ItemsSource="{Binding Path=Projects}" AutoGenerateColumns="False" Margin="8"
  21. AutomationProperties.AutomationId="ProjectsListGrid">
  22. <Controls:DataGrid.Columns>
  23. <Controls:DataGridTextColumn Header="System Name" Binding="{Binding Path=SystemName}" IsReadOnly="True" Width="*" />
  24. <Controls:DataGridTextColumn Header="App Name" Binding="{Binding Path=ApplicationName}" IsReadOnly="True" Width="*" />
  25. </Controls:DataGrid.Columns>
  26. </Controls:DataGrid>
  27. </Grid>
  28. </UserControl>

あとは、コードビハインドにて、コンストラクタに、ImportingConstructor アトリビュートを設定し、上記で作成した、ViewModel を インジェクションし、データコンテキストに設定するコードを記述。

  1. using System.ComponentModel.Composition;
  2. using System.Windows.Controls;
  3. using ProjectModule.ViewModels;
  4.  
  5. namespace ProjectModule.Views
  6. {
  7. [Export(typeof(ProjectListView))]
  8. public partial class ProjectListView : UserControl
  9. {
  10. [ImportingConstructor]
  11. public ProjectListView(ProjectListViewModel viewModel)
  12. {
  13. InitializeComponent();
  14.  
  15. this.DataContext = viewModel;
  16. }
  17. }
  18. }

実行

まずは、想定どおりに画面表示できた。

prism_handson15

Follow me!

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です