プログラムを中心とした個人的なメモ用のブログです。 タイトルは迷走中。
内容の保証はできませんのであしからずご了承ください。

2018/02/23

WPF で画面が表示されたタイミングで処理を行いたい場合

event_note2018/02/22 23:54

Behavior というのを使うと簡単にできそうなので、使ってみます。
また、MVVM のフレームワークとして Prism を使っています。

環境

  • Visual Studio 2017
  • .NET Framework 4.6.1

準備

NuGet で Expression.Blend.Sdk をインストールします。

PM> Install-Package Expression.Blend.Sdk

実装

View

以下のように実装します。

<Window x:Class="MyApp.View.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
        Title="MainWindow" Height="350" Width="300">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Loaded">
            <i:InvokeCommandAction Command="{Binding LoadedCommand}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
    <Grid>

    </Grid>
</Window>

Command に実行したいメソッドをバインドします。

ViewModel

コマンドを実装します。

using Prism.Commands;
using Prism.Mvvm;

namespace MyApp.ViewModels
{
    class ViewModel : BindableBase
    {
        public DelegateCommand LoadedCommand { get; }

        public ViewModel ()
        {
            LoadedCommand = new DelegateCommand(() =>
            {
                Console.WriteLine("hoge");
            });
        }
    }
}

参考 URL