開発記その 9 - T4 で ViewModel を生成 -

ViewModelのプロパティを定義するのがいちいちめんどくさかったので、T4 で生成するようなのを書いてみた。

T4 の先頭で以下のような感じで PropertyDef を複数並べるとそれに対応した C# のコードを生成します。

List<PropertyDef> propertyDefs = new List<PropertyDef>(){
  new PropertyDef("UserName",typeof(string)){
    Display = new DisplayAttr() {Name = "UserName" , ResourceType = "Assets.Resources.Strings"},
    Required = new RequiredAttr() { ErrorMessageResourceName = "ValidationErrorRequiredField", 
      ErrorMessageResourceType = "Assets.Resources.Strings"},
  },
  /...

以下のようなコードが生成されます。

private System.String userName_;
[Display(Name = "UserName", ResourceType = typeof(Assets.Resources.Strings))]
[Required(ErrorMessageResourceName = "ValidationErrorRequiredField", ErrorMessageResourceType = typeof(Assets.Resources.Strings))]
public System.String UserName {
  get { return this.userName_; }
  set {
    if( this.userName_ != value){
      bool cancel = false;
      System.String oldValue = this.userName_;
      PreUserNameChange(value, this.userName_, ref cancel);
      if(cancel){
        return;
      }
      
      this.userName_ = value;
      this.OnPropertyChanged("UserName");
      this.ValidateProperty("UserName", this.userName_);
      PostUserNameChange(value, oldValue);
    }
  }
}
		
partial void PreUserNameChange(System.String newValue, System.String currentValue, ref bool cancel);
		
partial void PostUserNameChange(System.String newValue, System.String oldValue);

この T4 と、メソッドとかを書くためのパーシャルのファイルをまとめて ItemTemplate にしてみました。

5 行くらい書くと、およそ25行くらいにコードを生成してくれます。約 5 倍。


で、実際のところほんまにこれ嬉しいのかって話なんですが、、、
スニペットで良いんでないの??と、作った張本人がおもってたりします。属性とかは手でガリガリ書かなだめですが、インテリセンスも効いてくれるのでたいした問題でないかと。。むしろ、自由に変更とかできるんでそっちのほうがいいかもとか。。

たぶん、コードで定義してるのがだめなんでしょうね。 DSL Tools とかで頑張って GUI で定義できるようにすれば、中途半端さ加減はなくなると思うのですが、それはそれでやりすぎな気もします。もうちょっとサラッとかけるようなのが欲しいですね。


まぁ、せっかく作ったんで今のところはこれで行きます。


※今回のチェックイン
http://moneybook.codeplex.com/SourceControl/changeset/changes/55776