MVVM
The model-view-viewmodel is a typically WPF pattern. It consists of a view that gets all the user input and forwards it to the viewmodel, typically by using commands. The view actively pulls the data from the viewmodel by using data binding. The model doesn’t know about the ViewModel and the ViewModel doesn’t know about the View.
(MVVM是典型的WPF设计模式。view通过命令将所有用户的输入传递给viewmodel。view通过数据绑定从viewmodel中获得数据。model不了解viewmodel的情况,viewmodel不了解view的情况)
Explaining MVVM through an example
Let’s create a sample Patient Management Application using MVVM. Going step by step we must first define our Model, then define the ViewModel and finally the View.
(通过一个例子来解释MVVM
让我使用MVVM创建一个简单的患者管理应用程序。按部就班我们必须首先定义Model(模式),然后定义ViewModel,最后定义View。)
Step 1 - Creating the Model:
(第一步:创建Model)
Def: The Model is often referred to as Domain Model, completely UI independent that stores the state and helps in the processing of the problem domain. In our example Model becomes the DOM object which is nothing but the patient entity. The sample below shows the patient Entity.
(Model通常指的是领域模型,存储了完全独立于UI的状态,帮助问题的处理。)
public class Patient
{
public int Id { get; set; }
public string Name { get; set; }
public Int64 MobileNumber { get; set; }
}
Step 2 – Creating the View Model
(第二步:创建ViewModel)
Def : The term means “Model of a View”, and can be thought of as abstraction of the view, but it also provides a specialization of the Model that the View can use for data-binding. In this latter role the ViewModel contains data-transformers that convert Model types into View types, and it contains Commands the View can use to interact with the Model. The ViewModel has been likened to a conceptual state of the data as opposed to the real state of the data in the Model.
(字面上看,ViewModel的意思是“视图的模型”,也可以被认为是view的抽象,但是它也是一个特殊化的模式,并且其view可以使用数据绑定。最新的角色,ViewModel包含了一个数据传送器,即将Model中的数据传送到View中。ViewModel中同样包含了一些命令,这样可以使得View可以与Model进行交互。)
Coming back to our example lets create the PatientViewModel which will expose the Properties(which contains the Data) and Commands (User actions) which will be binded to the view.
(回到我们的例子,让我们创建PatientViewModel,包括了内容和命令。)
Commands :
Def : The main idea is to move the whole presentation logic to the view model. This can be attained by using another feature of WPF, namely Commands. Commands can be bound like data and are supported by many elements as buttons, toggle buttons, menu items, checkboxes and input bindings. The goal here is not to have any line of logic in the code-behind of a view.
The View will execute commands on user action and the commands will be implemented in the ViewModel. To do this, you can’t use the standard WPF RoutedUIEvent, but you can easily develop your own command classes. A common way to do this is to create a command object that calls a delegate you specify.
Here is an example of how you can define a custom command class which you will later use when you are defining the commands in the ViewModel.
(我们主要的想法是把所有的逻辑展示放到ViewModel中。这样可以使用WPF的另一个特点:命令。Command可以向数据一样被约束,同时可以被很多种元素支持,比如按钮、三态按钮、菜单条目、复选框等。
View针对用户的动作执行命令,并且这些命令会执行于ViewModel中。为了这样奏效,我们不能使用WPF中标准的路由事件,但是我们可以轻松开发自己的command类。同样的方法就是创建一个command对象来调用你指定的委托。
这个例子教你如何定义一个通用的command类,这个类在稍后你定义ViewModel中commands的时候使用。)
public class RelayCommand : ICommand
{
readonly Action _execute;
readonly Predicate _canExecute;
public RelayCommand(Action execute)
: this(execute, null){}
public RelayCommand(Action execute,
Predicate canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_execute(parameter);
}
}
Coming back to our example, our sample app requires Add, Delete & Search functionalities. The sample shows how to implement Add command using the RelayCommand that we defined above. (回到我们的例子,我们这个简单的APP需要添加、删除、查找等功能。以添加命令为例,我们将演示如何使用我们上面定义的RelayCommand。)
public class PatientDetailViewModel: INotifyPropertyChanged
{
public ICommand AddPatientCmd
{
get { return _addPatientCmd; }
}
public PatientDetailViewModel()
{
_addPatientCmd = new RelayCommand(Add, CanAdd);
}
public bool CanAdd(object obj) { //Logic }
public void Add(object obj) { //Logic }
}
Step 3 – Creating the View
(第二步:创建View)
Def : A View is defined in XAML and should not have any logic in the code-behind. It binds to the view-model by only using data binding. The view involves mostly just setting up the UI and bindings to the ViewModel. The DataContext property for this control will be set to the ViewModel. As we have created the PatientViewModel all we need to do is create the PatientDetailView and then bind the ViewModel as the DataContext. The Sample here shows Property binding and Command binding.
(View在MAML中定义的,并且在后台代码中,View不应该含有任何的逻辑。它仅仅通过数据绑定将view绑定到viewmodel。)
<UserControl ...>
<!--Bind the View Model to the View. -->
<UserControl.DataContext>
<ViewModels:PatientDetailViewModel/>
</UserControl.DataContext>
....
<TextBox Name="TbxName"
....
Text="{Binding Path=Name}"/>
....
<Button Name="BtnAdd" Content="Add"
....
Command="{Binding AddPatientCmd}"/>
.....
</UserControl>
原文地址:http://blog.csdn.net/wangshubo1989/article/details/47828777