2012-02-28 67 views
0

我開始使用MVVM,但我一直困惑的東西,那裏是我的問題,我想在我的表中添加只有一個排,而這裏就是我這樣做的方法:如何在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(); 
    } 
} 

,我綁定datatatemplate到MyClass的,它的工作原理prefectly和調用SaveChanges到我的數據庫,但不更新我的觀點,在這種情況下,我想返回的ID,所以我把文本框並將其綁定到ID(prpoerty), 有什麼問題?我錯過了什麼? 我會appretiate任何幫助。

+0

當我改變Model.MyClass(實體模型類),並繼承了它從INotifyPropertyChanged的,就像這樣: INT ID; public virtual int Id { get {return id; } set { id = value; PropertyChanged(this,newPropertyChangedEventArgs(「Id」)); } } 它的工作原理,但我不知道應該從INotifyPropertyChanged繼承模型的類嗎? – 2012-02-28 10:09:57

回答

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); 
      } 
     } 
    } 
}