Update UI from ViewModel class (MVVM pattern) in WPF

后端 未结 6 1371
-上瘾入骨i
-上瘾入骨i 2020-12-29 12:59

I\'m using the MVVM pattern in my first WPF app and have a problem with something quite basic I assume.

When the user hits the \"save\" button on my view, a command

6条回答
  •  醉酒成梦
    2020-12-29 13:55

    You could always do something like this:

    public class SaveDemo : INotifyPropertyChanged
    {
      public event PropertyChangedEventHandler PropertyChanged;
      private bool _canSave;
    
      public bool CanSave
      {
        get { return _canSave; }
        set
        {
          if (_canSave != value)
          {
            _canSave = value;
            OnChange("CanSave");
          }
        }
      }
    
      public void Save()
      {
        _canSave = false;
    
        // Do the lengthy operation
        _canSave = true;
      }
    
      private void OnChange(string p)
      {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
          handler(this, new PropertyChangedEventArgs(p));
        }
      }
    }
    

    Then you could bind the IsEnabled property of the button to the CanSave property, and it will automatically be enabled/disabled. An alternative method, and one I would go with would be to use the Command CanExecute to sort this, but the idea is similar enough for you to work with.

提交回复
热议问题