如何在MVVM视图中显示数据更改?

时间:2012-02-28 06:11:43

标签: mvvm mvvm-light mvvm-toolkit

我开始使用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,它完美地工作并保存更改到我的数据库,但不更新我的视图,在这种情况下我想返回id,所以我把一个文本框并绑定到id(prpoerty ) 有什么问题?我错过了什么吗? 我愿意帮助你。

1 个答案:

答案 0 :(得分: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);
            }
        }
    }
}
相关问题