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");
});
}
}
}