for WPF developers
Home Profile Tips 全記事一覧

App.xaml.cs で OnStartup() メソッドをオーバーライドする

(2017/03/07 15:26:51 created.)

(2017/03/07 15:29:35 modified.)

App クラスの OnStartup() メソッドは、アプリケーション起動時に呼ばれるメソッドです。ここで View に対する DataContext プロパティの設定と、Show() メソッド呼び出しによるウィンドウの表示をおこないます。実際のコードは次のようになります。

title
  1. namespace Tips_Sample
  2. {
  3.     using System.Windows;
  4.     using Tips_Sample.ViewModels;
  5.     using Tips_Sample.Views;
  6.  
  7.     /// <summary>
  8.     /// App.xaml の相互作用ロジック
  9.     /// </summary>
  10.     public partial class App : Application
  11.     {
  12.         protected override void OnStartup(StartupEventArgs e)
  13.         {
  14.             base.OnStartup(e);
  15.  
  16.             var w = new MainView();
  17.             var vm = new MainViewModel();
  18.  
  19.             w.DataContext = vm;
  20.             w.Show();
  21.         }
  22.     }
  23. }