【问题标题】:WPF : How do I implement Save button enablingWPF:如何实现保存按钮启用
【发布时间】:2011-03-13 09:52:39
【问题描述】:

为应用程序设置保存状态的最简洁方法是什么,这样每当更新属性或内容时,“保存”选项就会启用。

例如,有一个菜单和工具栏的“保存”按钮。当 WPF 应用程序首次打开时,两个按钮都被禁用。当用户更新属性或文档时,按钮会变为启用状态,直到“保存”完成,此时它们会恢复为禁用状态。

【问题讨论】:

    标签: wpf


    【解决方案1】:

    IsEnabled 绑定到公开“IsDirty”或“HasBeenModified”布尔属性或类似属性的 ViewModel。如果模型因任何原因被修改,ViewModel 将监视模型的更改并将 IsDirty 设置为 true。保存后,可以告诉 ViewModel 将 IsDirty 设置为 false,从而禁用按钮。

    您使用的是模型-视图-视图模型模式,对吗?以下是有关模式的一些链接,可帮助您以防万一:

    http://en.wikipedia.org/wiki/Model_View_ViewModel

    http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

    http://www.wintellect.com/CS/blogs/jlikness/archive/2010/04/14/model-view-viewmodel-mvvm-explained.aspx

    【讨论】:

      【解决方案2】:

      您希望在同一个类中关注的所有属性吗?如果是这样,这样的事情会起作用:

      1. 让类派生自 INotifyPropertyChanged;
      2. 观察类的属性变化,并在发生变化时设置 IsDirty 标志
      3. 根据 IsDirty 标志为 Save 按钮设置 IsEnabled
      4. 执行保存命令时,设置 IsDirty=false

      通知类示例

      public class NotifyingClass : INotifyPropertyChanged
      {
              private string Property1Field;
              public string Property1
              {
                  get { return this.Property1Field; }
                  set { this.Property1Field = value; OnPropertyChanged("Property1"); }
              }
      
              private string Property2Field;
              public string Property2
              {
                  get { return this.Property2Field; }
                  set { this.Property2Field = value; OnPropertyChanged("Property2"); }
              }
      
              #region INotifyPropertyChanged Members
      
              public event PropertyChangedEventHandler PropertyChanged;
      
              public void OnPropertyChanged(string propertyName)
              {
                  if (PropertyChanged != null)
                  {
                      PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                  }
              }
      
              #endregion
      }
      

      观察属性变化

      public partial class MainWindow : Window
      {
          private bool isDirty;
      
          NotifyingClass MyProperties = new NotifyingClass();
      
          public MainWindow()
          {
              InitializeComponent();
      
              this.MyProperties.PropertyChanged += (s, e) =>
                  {
                      this.isDirty = true;
                  };
          }
      }
      

      如何设置禁用/启用状态取决于您正在执行的按钮/命令实现类型。如果您需要进一步的帮助,请告诉我您的操作方式(事件处理程序、RoutedCommand、RelayCommand 等),我会检查一下。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-07-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-18
        • 2011-12-16
        相关资源
        最近更新 更多