LoginSignup
1
3

More than 1 year has passed since last update.

WPF-MVVM開発手法

Last updated at Posted at 2021-05-13

誰かにMVVMを説明するとき用のメモです。MVVMを採用するメリットに関してはかなり局所的な内容になっているかもしれません。詳しくは下記の説明等を参照ください。
参考:https://qiita.com/yuutetu/items/ea175b73e1dbbfd355db

MVVM概要

Model(データ入出力管理)、View(UI処理)、ViewModel(ModelデータをUIデータに変換、及び、操作コマンドより対応したModel処理を呼び出す)で構成する開発手法です。

MVVM開発手法を採用するメリットとしては、下記が挙げられます。

  1. UIとビジネスロジック(データ・処理)が分離される
    具体的には、Formアプリケーションの一般的な構成では、UIロジックがModelのプロパティを直接参照しますが、この手法の場合、UI処理開発時にModelが必要となるか、UI処理の中に直接ビジネスロジックが存在することとなります。
    一方、MVVM開発手法では、例えばデータバインドを用いると、UIからは直接Modelのインスタンスを参照せず、対応するプロパティの名前でバインド定義する為、View開発時にModelのインスタンスは不要です。

  2. UIロジックとビジネスロジックを分離することで、コードの可読性が向上する。

データバインドの例

  1. <実行イメージ>
    ボタンを押下するとテキスト内の数値がカウントアップ
    image.png

  2. View処理:MainWindow.xaml

<Window ~省略~ />
    <Grid>
        <TextBox Text="{Binding Path=propString.Value}" />
        <Button Content="Button" Command="{Binding ShowMessageButtonCommand}"/>
    </Grid>
</Window>



3. ViewModel処理:MainWindowViewModel.cs

using Prism.Mvvm;
using Reactive.Bindings;

namespace prism_test.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
        /* テキストボックスに表示する文字列 */
        public ReactiveProperty<string> propString { get; set; } = new ReactiveProperty<string>();
        /* ボタン押下時のコマンドプロパティ */
        public ReactiveCommand ShowMessageButtonCommand { get; }

        /* コンストラクタ */
        public MainWindowViewModel()
        {
            propString.Value = "0";
            this.ShowMessageButtonCommand = new ReactiveCommand().WithSubscribe(this.buttonpush);
        }

        /* ボタン押下時のコマンド実体 */
        public void buttonpush()
        {
            propString.Value = (int.Parse(propString.Value) + 1).ToString(); ;
        }
    }
}
1
3
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
1
3