Mvvm-first-application

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

MVVM –最初のアプリケーション

この章では、単純な入力画面にMVVMパターンを使用する方法と、すでに慣れているWPFアプリケーションを学習します。

MVVMアプローチを使用する簡単な例を見てみましょう。

  • ステップ1 *-新しいWPFアプリケーションプロジェクトMVVMDemoを作成します。

最初のアプリケーションステップ1

  • ステップ2 *-3つのフォルダー(Model、ViewModel、およびViews)をプロジェクトに追加します。

最初のアプリケーションステップ2

  • ステップ3 *-モデルフォルダーにStudentModelクラスを追加し、そのクラスに以下のコードを貼り付けます
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));
         }
      }
   }
}
  • ステップ4 *-別のStudentViewModelクラスをViewModelフォルダーに追加し、次のコードを貼り付けます。
using MVVMDemo.Model;
using System.Collections.ObjectModel;

namespace MVVMDemo.ViewModel {

   public class StudentViewModel {

      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;
      }
   }
}
  • ステップ5 *-[ビュー]フォルダを右クリックし、[追加]> [新しいアイテム]を選択して、新しいユーザーコントロール(WPF)を追加します。

最初のアプリケーションステップ5

  • ステップ6 *-[追加]ボタンをクリックします。 これで、XAMLファイルが表示されます。 さまざまなUI要素を含むStudentView.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>
  • ステップ7 *-次のコードを使用して、StudentViewをMainPage.xamlファイルに追加します。
<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" Loaded = "StudentViewControl_Loaded"/>
   </Grid>

</Window>
  • ステップ8 *-次に、MainModel.xaml.csファイルのLoadedイベントの実装を示します。これにより、ViewModelからViewが更新されます。
using System.Windows;

namespace MVVMDemo {

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

   public partial class MainWindow : Window {

      public MainWindow() {
         InitializeComponent();
      }

      private void StudentViewControl_Loaded(object sender, RoutedEventArgs e) {
         MVVMDemo.ViewModel.StudentViewModel studentViewModelObject =
            new MVVMDemo.ViewModel.StudentViewModel();
         studentViewModelObject.LoadStudents();

         StudentViewControl.DataContext = studentViewModelObject;
      }
   }
}
  • ステップ9 *-上記のコードをコンパイルして実行すると、メインウィンドウに次の出力が表示されます。

最初のアプリケーションステップ9

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