WPF:如何实现“保存”按钮启用

时间:2010-07-08 15:07:16

标签: wpf

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

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

2 个答案:

答案 0 :(得分:1)

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

您正在使用Model-View-ViewModel模式,对吗?以下是关于模式的一些链接,以帮助您,以防万一:

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

答案 1 :(得分:0)

您希望在同一个班级中查看所有属性吗?如果是这样的话,这样的话会起作用:

  1. 让班级来自INotifyPropertyChanged;
  2. 从类中查看属性更改,并在有更改时设置IsDirty标志
  3. 根据IsDirty标志
  4. 为“保存”按钮设置IsEnabled
  5. 执行Save命令时,设置IsDirty = false
  6. 通知班级示例

    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,其他),我会检查出来。