差分

ナビゲーションに移動 検索に移動

ReactiveUI/ViewModelを作る

2,520 バイト追加, 2015年3月9日 (月) 10:39
ページの作成:「==基本== ReactiveUIのビューモデルはReactiveObjectクラスを基底クラスとする。 そしてプロパティセッターにおいてReactive...」
==基本==
ReactiveUIのビューモデルはReactiveObjectクラスを[[基底クラス]]とする。
そして[[プロパティ]]の[[セッター]]においてReactiveObjectクラスのRaiseAndSetIfChangedメソッドを噛ますことで値の変化を検出通知している。
<source lang="csharp">
using System;
using ReactiveUI;

public class MainViewModel : ReactiveObject
{
public string Name {
get { return _name; }
set { this.RaiseAndSetIfChanged(ref _name, value); }
}
private string _name;
}
</source>

==WhenAny==
WhenAnyメソッドを使うと引数に指定した複数のプロパティのうち、どれかひとつでも変化した場合の処理を書けるようだ。
<source lang="csharp">
using System;
using ReactiveUI;

public class MainViewModel : ReactiveObject
{
public string FirstName {
get { return _firstName; }
set { this.RaiseAndSetIfChanged(ref _firstName, value); }
}
private string _firstName;

public string LastName {
get { return _lastName; }
set { this.RaiseAndSetIfChanged(ref _lastName, value); }
}
private string _lastName;

/// <summary>
/// フルネームは読取専用にしておく
/// </summary>
/// <value>The full name.</value>
public string FullName{
get { return _fullName.Value; }
}
readonly ObservableAsPropertyHelper<string> _fullName;

/// <summary>
/// コンストラクタ
/// </summary>
public MainViewModel()
{
this.FirstName = "mono";
this.LastName = "book";

_fullName = this
.WhenAny(
// FirstNameか、LastNameに変化があったら、
x => x.FirstName, x => x.LastName,

// 結合した文字列を作り
(f, l) => string.Format("{0} {1}", f.Value, l.Value))

// FullNameにぶち込む
// Xamarin.MacのNSTextFieldなどの一部のビューではnullを許容していない関係で、
// initialValueに空文字を設定しておかないとバインドの際に落ちる。すごく嵌った。
.ToProperty(this, x => x.FullName, initialValue:"");
}
}
</source>

==関連項目==
*[[ReactiveUI]]

==参考文献==
{{reflist}}

{{stub}}
匿名利用者

案内メニュー