自从接触WPF后就不断听人提起MVVM。今天有空整理一下。
以前得C++(MFC)到c#的Winform都是直接编辑界面,拖控件,编辑控件的事件函数。感觉是一样的,所以我写WPF程序也是一个套路,感觉WPF并没有把UI和逻辑层分离开,和Winform区别不大,只是用Xaml语言代替了拖拽控件。
今天照着例子编写了一个整个的MVVM的程序,感受如下:
比如:model有功能函数:增删改查,界面有两个按钮,对应了两条命令,这两条命令可以对应到model里的任何一个方法函数上。或者另一个界面,有另外的按钮,也可以对应到model里的方法上,这时只需要替换view和viewmodel即可。
viewmodel层代码:
public class MainViewModel : ViewModelBase
{
#region 属性和构造函数
private LocalDb localDb;
private ObservableCollection
public ObservableCollection
{
get { return gridmodelList; }
set { gridmodelList = value; RaisePropertyChanged(); }
}
private string search;
public string Search
{
get { return search; }
set { search = value; RaisePropertyChanged(); }
}
public MainViewModel()
{
localDb = new LocalDb();
QueryCommand = new RelayCommand(this.Query);
ResetCommand = new RelayCommand(this.Reset);
EditCommand = new RelayCommand
DeleteCommand = new RelayCommand
AddCommand = new RelayCommand(this.Add);
}
#endregion
//命令
public RelayCommand QueryCommand { get; set; }
public RelayCommand ResetCommand { get; set; }
public RelayCommand AddCommand { get; set; }
public RelayCommand
public RelayCommand
public void Query()
{
List
if (string.IsNullOrEmpty(search))
{
students = localDb.Query();
}
else
{
students = localDb.QueryByName(search);
}
GridmodelList = new ObservableCollection
if (students != null)
{
students.ForEach(t =>
{ GridmodelList.Add(t); });
}
}
public void Reset()
{
this.search = string.Empty;
this.Query();
}
public void Edit(int Id)
{
var model = localDb.QueryById(Id);
if (model != null)
{
StudentWindow view = new StudentWindow(model);
var r = view.ShowDialog();
if (r.Value)
{
var newModel = GridmodelList.FirstOrDefault(t => t.Id == model.Id);
if (newModel != null)
{
newModel.Name = model.Name;
newModel.Age = model.Age;
newModel.Classes = model.Classes;
}
this.Query();
}
}
}
///
/// 删除
///
///
public void Delete(int Id)
{
var model = localDb.QueryById(Id);
if (model != null)
{
var r = MessageBox.Show($"确定要删除吗【{model.Name}】?", "提示", MessageBoxButton.YesNo);
if (r == MessageBoxResult.Yes)
{
localDb.Remove(Id);
this.Query();
}
}
}
///
/// 新增
///
public void Add()
{
Student model = new Student();
StudentWindow view = new StudentWindow(model);
var r = view.ShowDialog();
if (r.Value)
{
model.Id = GridmodelList.Max(t => t.Id) + 1;
localDb.Add(model);
this.Query();
}
}
}
}