LoginSignup
1
3

More than 5 years have passed since last update.

Xamarin FormsとReactiveUIでMVVMなハイブリッド?なアプリ開発するメモ

Last updated at Posted at 2016-03-10

Xamarin Formsを使ってスマホアプリを作る中で
ビューとビューモデル間のBindingをするのに
ReactiveUIを使ったので、使い方をメモします

開発環境

  • OS
    • Mac OS X El Capitan
  • Xamarin環境
    • Xamarin Studio 5.10.2 (build 56)
    • Mono 4.2.2
    • Xamarin Android Version: 6.0.1.10 (Indie Edition)
    • Xamarin iOS 9.4.2.27(Indie Edition)
  • ライブラリバージョンなど: Nugetパッケージからインストールします
    • Xamarin.Forms 2.1.0
    • reactiveui-xamforms 6.5.0
    • Rx 2.2.5
    • Splat 1.6.2

サンプル

ビューモデルの実装.

  • ReactiveUI.ReactiveObjectを継承したTestViewModelクラスを作成
  • プロパティAttrを定義し、setter内でRaiseAndSetIfChangedを実行
using ReactiveUI;

namespace Sample.ViewModels
{
    public class TestViewModel : ReactiveObject
    {
        #region properties
        private string attr= "";
        public string Attr { 
          get { return attr; }
          set { this.RaiseAndSetIfChanged(ref attr, value); } 
        }
        #endregion
    } 

ビューの実装

  • ReactiveUI.XamForms.ReactiveContentPageを継承したTestPageクラスを作成
    • 1.で定義したTestViewModelを型パラメータに指定します
  • ViewModelとViewのインスタンスをそれぞれ生成し、Bindメソッドを実行

    • ViewModelプロパティにTestViewModelのインスタンスを設定
    • attrEntryというビューを生成
      • テキスト入力フィールドを表すXamarin.Forms.Entryクラスを使用
    • TestViewModelのAttrプロパティとBindします
      • ビューで入力した値のビューモデルへの反映(及びその逆)が自動的に行われます
  • 注意

    • usingディレクティブで名前空間ReactiveUIがインポートが必要
      • これがないと下記のBindメソッドの定義が見つからずエラーになります
using System;
using Xamarin.Forms;
using ReactiveUI;
using ReactiveUI.XamForms;
using Sample.ViewModels;

namespace Sample {

  public class TestPage : ReactiveContentPage<TestViewModel>
  {
    private Entry attrEntry;
    public TestPage() {
      // ViewModelを生成
      this.ViewModel = new TestViewModel();
      // 入力フィールドを生成
      this.attrEntry = new Entry {
        /*中略*/
      };

      // ViewModelとViewを双方向バインド
      this.Bind (
          ViewModel, vm => vm.Attr, v => v.attrEntry.Text
      );

      Content = new StackLayout {
        HorizontalOptions = LayoutOptions.FillAndExpand,
        VerticalOptions = LayoutOptions.Center,
        Children = {
          this.attrEntry
        }
      };
    }
  }
}

以上!

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