LoginSignup
3
7

More than 5 years have passed since last update.

MVVM Light Toolkitで簡易アプリ作成

Last updated at Posted at 2019-02-17

はじめに

WPF(MVVM)でのHello World的なアプリ作成を試してみる。
たぶんもっとスマートな方法があると思うけど…。

環境

  • Windows 10
  • Visual Studio 2017
  • MVVM Light Toolkit

MVVM Light Toolkitでのサンプルとしては、こちらでサンプルコードが提供されている。
今回の簡易アプリ作成の上で参考にした。

プロジェクト作成

WPFでプロジェクト作成し、

ツール → NuGetパッケージマネージャ → ソリューションのNuGetパッケージの管理

でパッケージマネージャを表示させ、下記パッケージを導入する。

  • MvvmLight
  • ReactiveProperty

インストールに成功すると、ViewModelフォルダが生成されMainViewModel.cs, ViewModelLocator.csが作成される。
自分の環境では、生成されたViewModelLocator.csにエラーが出てビルドできず、下記修正を加えた。

ViewModelLocator.cs
// using GalaSoft.MvvmLight; // コメントアウト
using CommonServiceLocator; // 追加
using GalaSoft.MvvmLight.Ioc;
// using Microsoft.Practices.ServiceLocation; // コメントアウト

Viewに下記を追加する。

MainWindow.xaml
<Window x:Class="WpfMvvmTrain01.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfMvvmTrain01"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800"
        DataContext="{Binding Source={StaticResource Locator}, Path=Main}">
        <!-- ↑ DataContext を追加 -->

なんか表示させる

MainViewModel.cs の MainViewModelクラスに適当にプロパティを追加して動かしてみる。
数字を表示させ、ボタンで増減させてみる。

MainViewModel.cs
        public MainViewModel()
        {
            this.Number = new ReactiveProperty<int>();

            this.IncrementNum = new ReactiveCommand();
            this.IncrementNum.Subscribe(_ => this.Number.Value++);

            this.DecrementNum = new ReactiveCommand();
            this.DecrementNum.Subscribe(_ => this.Number.Value--);
        }

        public ReactiveProperty<int> Number { get; set; }
        public ReactiveCommand IncrementNum { get; private set; }
        public ReactiveCommand DecrementNum { get; private set; }
MainWindow.xaml
    <Grid>
        <StackPanel>
            <TextBlock Text="{Binding Number.Value}"/>
            <Button Content="increment" Command="{Binding IncrementNum, Mode=OneWay}"/>
            <Button Content="decrement" Command="{Binding DecrementNum, Mode=OneWay}"/>
        </StackPanel>
    </Grid>

実行結果

rapture_20190217174145.png

ボタンを押すと左上の数値が変動する。
自分でほとんどコードを書くことなく動作させることができた。

3
7
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
3
7