在MEF模式下,通常是viewmodel发布一个事件,另一个viewmodel接收并处理事件,事件处理通常会加载View。如下代码:
- ICommand addUser;
- public ICommand AddUser
- {
- get
- {
- if(addUser ==null)
- addUser = new Microsoft.Practices.Prism.Commands.DelegateCommand(OnAddingUser);
- return addUser;
- }
- }
- void OnAddingUser()
- {
- var viewmodel = ServiceLocator.Current.GetInstance<IViewModel>("EditUserViewModel");
- this.CurrentUser = this.userService.AddUser();
- this.eventAggregator.GetEvent<CommandEvent>().Publish(new CommandEventPara() { CommandName = "EditUser", Entity = this.CurrentUser });
- }
-
- void OnEditUserComplete(CommandEventPara para)
- {
- this.userService.SaveChangesAsync();
- }
AddUser事件处理程序OnAddingUser,首先实例化一个EditUserVIewmodel,在EditUserViewModel中加入事件接收处理程序,然后在发布事件,这样EditUserVIewmodel就能够响应事件,进行事件 处理。再看看EditUserVIewmodel初始化过程
- [ImportingConstructor]
- public EditUserViewModel(IEventAggregator _eventAggregator, IRegionManager _regionManager)
- {
- eventAggregator = _eventAggregator;
- regionManager = _regionManager;
- this.eventAggregator.GetEvent<CommandEvent>().Subscribe(Onloading, ThreadOption.UIThread, true, p => p.CommandName == "EditUser");
- userService = ServiceLocator.Current.GetInstance<IService>("UserService") as UserService;
- groupService = ServiceLocator.Current.GetInstance<IService>("GroupService") as GroupService; ;
- groupService.GetGroupListComplete += new EventHandler<EntityResultsArgs<T_SYS_GROUP>>(groupService_GetGroupListComplete);
- groupService.GetGroupListAsync();
-
- }
这里使用的是MEF构造注入,构造函数中进一步实例化一些服务类用来获取Model或列表数据,由于silverlight是异步模式,这样会导致事件响应后部分数据还未获取成功,比如此例中groupservice要获取的grouplist,这样必然导致界面显示出来后还有部分组件数据未能有效加载。下面是响应事件 处理程序,并弹出窗口,此方法将优先在
groupService_GetGroupListComplete方法执行。这样导致ChildWindow中的Combobox数据无法正确绑定。
- void Onloading(CommandEventPara para)
- {
- if (para.Entity != null)
- {
- this.CurrentUser = para.Entity as T_SYS_USER;
- this.Userid = (para.Entity as T_SYS_USER).SACCOUNTID;
- this.AccountCode = (para.Entity as T_SYS_USER).SACCOUNTCODE;
- this.CompanyCode = (para.Entity as T_SYS_USER).SCOMPANYCODE;
- this.UserName = (para.Entity as T_SYS_USER).SUSERNAME;
- this.Mobile = (para.Entity as T_SYS_USER).SMOBILE;
- this.Phone = (para.Entity as T_SYS_USER).SPHONE;
- ChildWindow view = ServiceLocator.Current.GetInstance<IView>("AddUserView") as ChildWindow;
-
- view.Show();
- }
- }
处理办法:由于Combobox的selectvalue绑定的是CompanyCode属性,所以我们需要在
groupService_GetGroupListComplete函数中加入一个引发CompanyCode属性变化的事件,该事件会触发UI进行数据更新,这样就能够解决数据正确加载绑定了。
- private string _companyCode;
- [Required(ErrorMessage = "单位必选")]
- public string CompanyCode
- {
- get { return _companyCode; }
- set
- {
- _companyCode = value;
- RaisePropertyChanged("CompanyCode");
- }
- }
- void groupService_GetGroupListComplete(object sender, EntityResultsArgs<T_SYS_GROUP> e)
- {
-
- if (!e.HasError)
- {
- this.GroupList = new ObservableCollection<T_SYS_GROUP>(e.Results);
- RaisePropertyChanged("CompanyCode");
-
- }
- }