LoginSignup
2
1

More than 3 years have passed since last update.

ViewModel と移譲コマンド

Posted at

はじめに

オレオレ解釈の覚え書き その8

移譲コマンドについてまとめます。

本文

移譲コマンドとは ViewModel で宣言されるデリゲートです。View からバインドされることを前提にしており、コントロールの決められたプロパティとバインドすることで、コントロールへの操作に対応する処理を ViewModel で実装することができます。

移譲コマンドは ICommand インターフェースとして公開され、これを実装するクラスは、Prism であれば DelegateCommand、Livet であれば ViewModelCommand、MVVM Light Toolkit であれば RelayCommand といった具合にフレームワーク独自の形で提供されています。

今回は Prism を使い、画面上のボタンがクリックされたときに実行される処理を ViewModel に移譲してみます。ViewModel に ICommand インターフェースのプロパティを宣言し、DelegateCommand クラスで初期化します。View には Button コントロールを配置し、Command プロパティでバインドします。これにより、画面に配置されたボタンがクリックされると、ViewModel のメソッドが呼び出されるようになります。

ViewModel
using Prism.Commands;
using System.Windows.Input;

namespace TestApp.ViewModels
{
    public class MainWindowViewModel
    {
        public ICommand ShowMessageCommand { get; }

        public MainWindowViewModel()
        {
            this.ShowMessageCommand = new DelegateCommand(() => this.ShowMessage());
        }

        private void ShowMessage()
        {
            // メッセージを表示する処理
        }
    }
}
View
<Window x:Class="TestApp.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
        xmlns:p="http://prismlibrary.com/"
        p:ViewModelLocator.AutoWireViewModel="True">
    <Grid>
        <Button Command="{Binding ShowMessageCommand, Mode=Onetime}" Content="メッセージ表示" VerticalAlignment="Center" HorizontalAlignment="Center"/>
    </Grid>
</Window>

おわりに

View を起点にした処理を定義するための移譲コマンドについてでした。
原則的には View はビジネスロジックを扱えないため、処理を ViewModel に任せる必要があり、本稿の移譲コマンドを使用します。逆に ViewModel では描画ロジックを扱えないため、前回の相互作用処理を使い View に依頼します。これらを組み合わせて両層でやり取りをしつつ、処理を組み立てていきましょう。

次回は MVVM を語るうえで特に重要な仕組みである、変更通知プロパティについてまとめます。(これがなければ ViewModel のプロパティの変更を View に反映できません。本来は最初にやるべきでした。)

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1