Mvvm-hooking-up-views

提供:Dev Guides
移動先:案内検索

MVVM –ビューの接続

この章では、ViewModelにビューを接続するさまざまな方法について説明します。 まず、XAMLで宣言できるView first構造を見てみましょう。 メインウィンドウからビューを接続した最後の章の例を見てきたように。 次に、ビューを接続する他の方法を見ていきます。

この章でも同じ例を使用します。 以下は、同じModelクラスの実装です。

using System.ComponentModel;

namespace MVVMDemo.Model {

   public class StudentModel {}

   public class Student : INotifyPropertyChanged {
      private string firstName;
      private string lastName;

      public string FirstName {
         get { return firstName; }

         set {
            if (firstName != value) {
               firstName = value;
               RaisePropertyChanged("FirstName");
               RaisePropertyChanged("FullName");
            }
         }
      }

      public string LastName {
         get { return lastName; }

         set {
            if (lastName != value) {
               lastName = value;
               RaisePropertyChanged("LastName");
               RaisePropertyChanged("FullName");
            }
         }
      }

      public string FullName {
         get {
            return firstName + " " + lastName;
         }
      }

      public event PropertyChangedEventHandler PropertyChanged;

      private void RaisePropertyChanged(string property) {
         if (PropertyChanged != null) {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
         }
      }
   }
}

ViewModelクラスの実装は次のとおりです。 今回は、LoadStudentsメソッドがデフォルトのコンストラクターで呼び出されます。

using MVVMDemo.Model;
using System.Collections.ObjectModel;

namespace MVVMDemo.ViewModel{

   public class StudentViewModel {

      public StudentViewModel() {
         LoadStudents();
      }

      public ObservableCollection<Student> Students {
         get;
         set;
      }

      public void LoadStudents() {
         ObservableCollection<Student> students = new ObservableCollection<Student>();

         students.Add(new Student { FirstName = "Mark", LastName = "Allain" });
         students.Add(new Student { FirstName = "Allen", LastName = "Brown" });
         students.Add(new Student { FirstName = "Linda", LastName = "Hamerski" });

         Students = students;
      }
   }
}

ビューがウィンドウ、ユーザーコントロール、またはページのいずれであっても、パーサーは通常、上から下、左から右に機能します。 各要素に遭遇すると、デフォルトのコンストラクタを呼び出します。 ビューを作成するには2つの方法があります。 どれでも使用できます。

  • XAMLで最初の構築を表示
  • コードビハインドで最初の構造を表示

XAMLで最初の構築を表示

1つの方法は、次のコードに示すように、DataContextプロパティのセッターにネストされた要素としてViewModelを追加するだけです。

<UserControl.DataContext>
   <viewModel:StudentViewModel/>
</UserControl.DataContext>

完全なView XAMLファイルを次に示します。

<UserControl x:Class="MVVMDemo.Views.StudentView"
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
   xmlns:local = "clr-namespace:MVVMDemo.Views"
   xmlns:viewModel = "clr-namespace:MVVMDemo.ViewModel"
   mc:Ignorable = "d"
   d:DesignHeight = "300" d:DesignWidth = "300">

   <UserControl.DataContext>
      <viewModel:StudentViewModel/>
   </UserControl.DataContext>

   <Grid>
      <StackPanel HorizontalAlignment = "Left">
         <ItemsControl ItemsSource = "{Binding Path = Students}">

            <ItemsControl.ItemTemplate>
               <DataTemplate>

                  <StackPanel Orientation = "Horizontal">
                     <TextBox Text = "{Binding Path = FirstName, Mode = TwoWay}"
                        Width = "100" Margin = "3 5 3 5"/>

                      <TextBox Text = "{Binding Path = LastName, Mode = TwoWay}"
                        Width = "100" Margin = "0 5 3 5"/>

                     <TextBlock Text = "{Binding Path = FullName, Mode = OneWay}"
                        Margin = "0 5 3 5"/>

                  </StackPanel>

               </DataTemplate>
            </ItemsControl.ItemTemplate>

         </ItemsControl>
      </StackPanel>
   </Grid>

</UserControl>

コードビハインドで最初の構造を表示

もう1つの方法は、Viewを最初に構築できることです。インスタンスでDataContextプロパティを設定して、Viewのコードビハインドでビューモデルを構築するだけです。

通常、DataContextプロパティはビューのコンストラクターメソッドで設定されますが、ビューのLoadイベントが発生するまで構築を延期することもできます。

using System.Windows.Controls;

namespace MVVMDemo.Views {

  ///<summary>
     ///Interaction logic for StudentView.xaml
  ///</summary>

   public partial class StudentView : UserControl {
      public StudentView() {
         InitializeComponent();
         this.DataContext = new MVVMDemo.ViewModel.StudentViewModel();
      }
   }
}

XAMLの代わりに分離コードでビューモデルを構築する理由の1つは、Viewモデルコンストラクターがパラメーターを取ることですが、XAML解析では既定のコンストラクターで定義されている場合にのみ要素を構築できることです。

この場合、ViewのXAMLファイルは次のコードのようになります。

<UserControl x:Class = "MVVMDemo.Views.StudentView"
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
   xmlns:local = "clr-namespace:MVVMDemo.Views"
   mc:Ignorable = "d"
   d:DesignHeight = "300"
   d:DesignWidth = "300">

   <Grid>
      <StackPanel HorizontalAlignment = "Left">
         <ItemsControl ItemsSource = "{Binding Path = Students}">

            <ItemsControl.ItemTemplate>
               <DataTemplate>

                  <StackPanel Orientation = "Horizontal"<
                     <TextBox Text = "{Binding Path = FirstName, Mode = TwoWay}"
                        Width = "100" Margin = "3 5 3 5"/>

                     <TextBox Text = "{Binding Path = LastName, Mode = TwoWay}"
                        Width = "100" Margin = "0 5 3 5"/>

                     <TextBlock Text = "{Binding Path = FullName, Mode = OneWay}"
                        Margin = "0 5 3 5"/>

                  </StackPanel>

               </DataTemplate>
            </ItemsControl.ItemTemplate>

         </ItemsControl>
      </StackPanel>
   </Grid>

</UserControl>

MainWindow.XAMLファイルに示されているように、このビューをMainWindowで宣言できます。

<Window x:Class = "MVVMDemo.MainWindow"
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
   xmlns:local = "clr-namespace:MVVMDemo"
   xmlns:views = "clr-namespace:MVVMDemo.Views"
   mc:Ignorable = "d"
   Title = "MainWindow" Height = "350" Width = "525">

   <Grid>
      <views:StudentView x:Name = "StudentViewControl"/>
   </Grid>

</Window>

上記のコードをコンパイルして実行すると、メインウィンドウに次の出力が表示されます。

ビューのメインウィンドウの接続

理解を深めるために、上記の例を段階的に実行することをお勧めします。