LoginSignup
24
24

More than 5 years have passed since last update.

WPF ViewModel から Viewへの通知

Last updated at Posted at 2014-04-03

WPFでは、ViewからViewModelへの通知を行う機能としてICommandインターフェイスを提供してくれていますが、
ViewModelからViewへの通知を行うための仕組みは用意されていません。

しかし、Windowをクローズしたいとか、ViewModelからViewへ通知を行いたいというケースは多いです。

イベント(デリゲート)を利用する。

WPFにはViewModelからViewへ通知する特別な機能はありませんが、View は DataContext 経由で ViewModel への参照を
保持しているので、普通に ViewModel のパブリックなプロパティやメソッド、イベント、デレゲートにアクセスすることが
できます。ViewModelからViewへの通知はViewModelにイベント(デリゲート)を設定することで行えます。特別な機能は
必要ないということですね。

サンプルとしてViewModel から Viewをクローズするコードを示します。

ViewModelからViewにWindowをクローズするよう通知するサンプル

ViewModel.cs
class ViewModel : ViewModelBase
{
    // イベント
    public event EventHandler<EventArgs> CloseView;

    // コマンド
    public ICommand CloseCommand { get; private set; }

    // コンストラクタ
    public ViewModel()
    {
        CloseCommand = CreateCommand(v => 
            { 
                if (CloseView != null) 
                    CloseView(this, EventArgs.Empty); 
            });
    }
}
MainWindow.xaml.cs
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        DataContextChanged += (o, e) =>
            {
                ViewModel vm = DataContext as ViewModel;
                if (vm != null)
                {
                    vm.CloseView += (sender, arg) => { Close(); };
                }
            };

        DataContext = new ViewModel();
    }
}
MainWindow.xaml
<Window x:Class="WpfTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfTest"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Content="閉じる" FontSize="14" Padding="20,10,20,10" VerticalAlignment="Center" HorizontalAlignment="Center" Command="{Binding CloseCommand}" />
    </Grid>
</Window>
24
24
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
24
24