2012-02-28 7 views
0

私はMVVMを使用し始めているが、私は何かについて混乱してきたが、そこに私は私のテーブルに1行のみを追加したい、私の問題だし、ここに私はこれを行う方法です。MVVMビューでデータ変更を表示する方法は?

のViewModelクラス:

をその後
// Model.MyClass is my entity 
    Model.MyClass myClass; 
    public Model.MyClass MyClass 
    { 
     get 
     { 
      return myClass; 
     } 
     set 
     { 
      myClass= value; 
      base.OnPropertyChanged(() => MyClass); 
     } 
    } 

    context = new myEntities(); 
    myclass=new Model.MyClass(); 
    context.MyClass.AddObject(MyClass); 

public ICommand SaveCommand 
{ 
    get { return new BaseCommand(Save); } 
} 
void Save() 
{ 
    if (DefaultSpecItem != null) 
    { 
     context.SaveChanges(); 
    } 
} 

と私はMyClassのにdatatatemplateをバインドし、それは私のデータベースにprefectlyとのSaveChanges動作しますが、私はIDを返すようにしたい、この場合には、私の見解を更新しません、だから私はテキストボックスを入れて、id(prpoerty)にバインドする、 何が問題なのですか?何か不足していますか? 私はどんな助けにappretiateだろう。

+0

私はModel.MyClass(エンティティモデルクラス)を変更し、このように、INotifyPropertyChangedのからそれを継承したとき: int型のID。 public virtual int Id { get {return id; } セット { id = value; PropertyChanged(this、newPropertyChangedEventArgs( "Id")); } } これは動作しますが、モデルのクラスをINotifyPropertyChangedから継承する必要があるかどうかわかりません。 –

答えて

1

バインディングを実行するには、INotifyPropertyChangedを実装する必要があります。通常、この実装は、モデルのプロパティをラップするビューモデルに移動され、変更通知が追加されます。しかし、モデル内で直接行うのは間違いではありません。この場合、通常、プロパティを介してビューモデルでモデルに直接アクセスできるようになり、ビンディングにドット表記を使用します(すなわち、VM.Model.Property)。

個人的には、柔軟性が高く、バインディングをより理解しやすいようにプロパティをラップすることをお勧めします。

だからここはあなたのモデルに基づいた例である:

public class ModelViewModel : ViewModelBase { 
    public ModelViewModel() { 
     // Obtain model from service depending on whether in design mode 
     // or runtime mode use this.IsDesignTime to detemine which data to load. 
     // For sample just create a new model 
     this._currentData = Model.MyClass(); 
    } 

    private Model.MyClass _currentData; 

    public static string FirstPropertyName = "FirstProperty"; 

    public string FirstProperty { 
     get { return _currentData.FirstProperty; } 
     set { 
      if (_currentData.FirstProperty != value) { 
       _currentData.FirstProperty = value; 
       RaisePropertyChanged(FirstPropertyName); 
      } 
     } 
    } 

    // add additional model properties here 

    // add additional view model properties - i.e. properties needed by the 
    // view, but not reflected in the underlying model - here, e.g. 

    public string IsButtonEnabledPropertyName = "IsButtonEnabled"; 

    private bool _isButtonEnabled = true; 

    public bool IsButtonEnabled { 
     get { return _isButtonEnabled; } 
     set { 
      if (_isButtonEnabled != value) { 
       _isButtonEnabled = value; 
       RaisePropertyChanged(IsButtonEnabledPropertyName); 
      } 
     } 
    } 
}