0

私はMVVMを使い始めていますが、何かについて混乱しています。問題があります。テーブルに1行だけ追加したいのですが、これを行う方法は次のとおりです。

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)にバインドします。問題?何かが足りないのですか?私はどんな助けにも感謝します。

4

1 に答える 1

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);
            }
        }
    }
}
于 2012-03-02T07:18:21.023 に答える