WPF MVVM

MVVM全称:Model-View-ViewModel

优点:MVVM的引入使程序实现了松耦合设计,UI层与业务逻辑可以并行设计

1、Model:对现实世界的抽象

比如:需要做一个学校的管理系统,学校包括学生和老师,此时可以把老师和学生抽象成老师类及学生类。

老师类:具有教学及备课等属性

学生类:具有学习的属性

将这些实实在在的现实事物抽象成类。Model层永远不知道View层的存在。

2、ViewModel:对View层的抽象

还是以学校为例:在View界面上有需要显示老师的姓名、性别、教的什么课程,显示学生的姓名、性别、年龄、年级,此时可以将这些抽象成具体的ViewModel模型,包含老师及学生要显示的属性以及命令。

说明:属性需要具有通知UI更新的能力,即ViewModel要继承:NotificationObject类。

属性:实现接口INotifyPropertyChanged,自动和UI层交互。

集合:它的类型一般是ObservableCollection,因此,任何UI元素绑定到它,不管这个集合什么时候改变,都可以自动的与UI交互。

命令:要继承ICommand接口。

为了理解MVVM,下面一个简单的例子:

(a)、实现NotificationObject类:

public class NotificationObject : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void RaisePropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

(b)、实现DelegateCommand类

class DelegateCommand : ICommand
    {
        public bool CanExecute(object parameter)
        {
            if (this.CanExecuteFunc == null)
            {
                return true;
            }

            return this.CanExecuteFunc(parameter);
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            if (this.ExecuteAction == null)
            {
                return;
            }
            this.ExecuteAction(parameter);
        }

        public Action<object> ExecuteAction { get; set; }
        public Func<object, bool> CanExecuteFunc { get; set; }
    }

(c)、实现ViewModel类

class MainWindowViewModel : NotificationObject
    {
        private double _name;

        public double Name
        {
            get { return _name; }
            set
            {
                _name = value;
                this.RaisePropertyChanged("Name");
            }
        }

        public DelegateCommand SaveCommand { get; set; }

        private void Save(object parameter)
        {
            this.Name += "保存";
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.ShowDialog();
        }

        public MainWindowViewModel()
        {
            this.SaveCommand = new DelegateCommand();
            this.SaveCommand.ExecuteAction = new Action<object>(this.Save);
        }

3、View:UI层

<TextBox Text="{Binding Name}" />
<Button Content="Save" Command="{Binding SaveCommand}" />

在代码隐藏中加入

public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainWindowViewModel();
        }

以上只是简陋的MVVM框架结构,只是帮助理解,而在实际的项目中,我们没必要再去编写NotificationObject及DelegateCommand这两个类,我们可以引用Prisim中的类即可,在项目中加入Microsoft.Practices.Prism.dll,NotificationObject 引用 using Microsoft.Practices.Prism.ViewModel;DelegateCommand引用using Microsoft.Practices.Prism.Commands;

原文地址:https://www.cnblogs.com/sunqiliang/p/5386281.html