1.什么是MVVM
Model-View-ViewModel.
Model:系统中的对象,可包含属性和行为(就是一个类,是对现实事物的抽象)。
View:Xmal界面,负责与用户交互,接收用户输入,把数据展现给客户。显示数据和发送命令。
ViewModel:负责收集需要绑定的数据和命令,聚合Model对象,通过View类的DataContext属性绑定到View,同时可以处理一些UI逻辑,显示的数据对应着ViewModel中的Property,执行的命令对应着ViewModel中的command。提供数据和执行命令。
2.简单示例
如下是一个简单的mvvm框架,在界面点击按钮即可在显示区域显示学生基本信息,用了prism框架:
ViewModel:
using Prism.Mvvm;
using Prism.Commands;
using System.Dynamic;
using SimpleMvvmExmple.Models;
namespace SimpleMvvmExmple.ViewModels
{
internal class MainWindowViewModel:BindableBase //NotifitionObject
{
private string stuInfo;
public string StuInfo
{
get { return stuInfo; }
set
{
//result = value;
//this.RaisePropertyChange("Result");
SetProperty(ref stuInfo, value);
}
}
static Student student = new Student() { Id =1, Name="zhangsan", Age=13 };
string stu = student.Id.ToString() + " " + student.Name + " " + (student.Age.ToString());
public void stuCommand()
{
this.StuInfo = stu;
}
public DelegateCommand GetStuInfoCommand { get; set; }
public MainWindowViewModel()
{
this.GetStuInfoCommand = new DelegateCommand(stuCommand);
//AllCommand.ExecuteAction = new Action<object>(mymathCommand);
}
}
}
Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimpleMvvmExmple.Models
{
internal class Student
{
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
}
}
View:
<Grid>
<TextBlock Background="LightBlue" HorizontalAlignment="Left" Margin="29,24,0,0" TextWrapping="Wrap" Text="{Binding StuInfo}" VerticalAlignment="Top" Height="133" Width="371"/>
<Button Content="显示信息" HorizontalAlignment="Left" Margin="280,174,0,0" VerticalAlignment="Top" Height="43" Width="120" Command="{Binding GetStuInfoCommand}"/>
</Grid>