MVVM,一言以蔽之,即使用ViewModel调用DAL层(或是其他层)来对Model进行增删查改操作,然后通过绑定和命令将数据展示到View中。
调用DAL层操作数据,没什么可说的。关于绑定,本人的上一篇文章 wpf之数据绑定基础 中已有涉及。本文将通过一个简单而完整的例子来讲述数据的展示及用户操作的绑定,且看本人慢慢道来。
Model还是依旧使用上一篇文章中的,下面是两个Model的代码。
public classModelBase : INotifyPropertyChanged
{public eventPropertyChangedEventHandler PropertyChanged;public void OnPropertyChanged(stringpropertyName)
{if (PropertyChanged != null)
{
PropertyChanged(this, newPropertyChangedEventArgs(propertyName));
}
}
}
public classPerson : ModelBase
{private stringId;public stringID
{get { returnId; }set { Id = value; OnPropertyChanged("ID"); }
}private stringname;public stringName
{get { returnname; }set { name = value; OnPropertyChanged("Name"); }
}
}
现在我们来准备ViewModel,首先我们要显示数据集,所以ViewModel中需要有一个Person的集合(这里用BindingList)。
下面即是读取、显示数据的代码,注数据均为虚拟的,未访问数据库。
public classViewModel : ModelBase
{private BindingList_people;public BindingListPeople
{get { return _people ?? (_people = new BindingList()); }set { _people = value; OnPropertyChanged("People"); }
}publicViewModel()
{
People=GetAll();
}public BindingListGetAll()
{
BindingList people = new BindingList();for (int i = 1; i <= 10; i++)
{
people.Add(new Person() { ID = i.ToString(), Name = "Person" +i.ToString() });
}returnpeople;
}
}
现在我们将数据绑定到界面,并在后台代码中设置数据源 this.DataContext = new ViewModel(),这里直接将数据源设置到整个窗体了。好了,现在数据已经可以展示在界面上了。
上面说过,一般我们会对数据进行增删查改的操作,目前我们看到的只是查,还有增删改需要与用户交互。下面我就展示下如何添加数据,而修改和删除则仅仅是逻辑和视图的不同而已,依葫芦画瓢即可。
为了将用户操作从后台提取到ViewModel中,需要绑定命令。于是我们可以通过委托将方法传递给自定义命令,下面是本人封装的一个简单自定义命令。事实上自定义命令只需要实现ICommand接口即可,读者自己可以根据需求去封装,不过目前很多人都使用Prism中的DelegateCommand或是将其修改为自己的。
public classCustomCommand : ICommand
{privateAction _executeMethod;private Func_canExecuteMethod;public CustomCommand(Action executeMethod, FunccanExecuteMethod)
{if (executeMethod == null)
{throw new ArgumentNullException("executeMethod");
}
_executeMethod=executeMethod;
_canExecuteMethod=canExecuteMethod;
}public eventEventHandler CanExecuteChanged;public bool CanExecute(objectparameter)
{if (_canExecuteMethod == null) return true;return_canExecuteMethod();
}public void Execute(objectparameter)
{if (_executeMethod != null)
_executeMethod();
}
}
现在我们再向ViewModel中添加一个命令来实现数据添加的操作。由于我们要添加数据(本示例只演示一个添加操作),所以我们还需要一个临时的Person对象来绑定用户数据,然后将其添加到集合中,进而将这个集合保存到数据库。
privatePerson _person;publicPerson person
{get { return _person ?? (_person = newPerson()); }set { _person = value; OnPropertyChanged("person"); }
}privateCustomCommand _addCmd;publicCustomCommand AddCmd
{get { return _addCmd ?? (_addCmd = newCustomCommand(Add, CanAdd)); }
}public voidAdd()
{if (person != null) People.Add(person);
}public boolCanAdd()
{return People != null && person != null;
}
接下来,将这个Person对象和操作绑定到界面就大功告成了。
下面是运行图。