码迷,mamicode.com
首页 > Windows程序 > 详细

wpf viewmodel之间的通信

时间:2015-04-27 18:09:06      阅读:488      评论:0      收藏:0      [点我收藏+]

标签:

使用Prism第三方框架实现ViewModel之间的通信

 

创建类继承自UnityBootstrapper

public class Bootstrapper : UnityBootstrapper
{
protected override System.Windows.DependencyObject CreateShell()
{
MainWindow shell = Container.Resolve<MainWindow>();
shell.Show();
return shell;
}
}

 

自定义事件

class UserChangedEvent : CompositePresentationEvent<ClsDataManage.wordtest>
{
}

 

在app.xaml.cs文件中设置启动页

protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);

var bootstrapper = new Bootstrapper();
bootstrapper.Run();
}

 

在viewmodel中注册事件

public class WordManageViewModel
{

  protected IEventAggregator eventAggregator;

  public WordManageViewModel()
  {
    //设计时状态判断
    if (System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv")
    {
      return;
    }
    //获取事件聚合器
    this.eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>(ClsDataManage.wordtest);

}

 

public void Insert(object name)
{

    //发布事件
    base.eventAggregator.GetEvent<UserChangedEvent>().Publish(wordtest);

}

 

在另一个ViewModel中接收事件处理

public class TestManageViewModel
{

  protected IEventAggregator eventAggregatorEx;
  protected SubscriptionToken token;

  public TestManageViewModel()
  {
    if (System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv")
    {
      return;
    }

    //订阅事件
    eventAggregatorEx = ServiceLocator.Current.GetInstance<IEventAggregator>();
    token = eventAggregatorEx.GetEvent<UserChangedEvent>().Subscribe(UserChanged);

  }

  //事件触发
  public void UserChanged(ClsDataManage.wordtest wordtest)
  {

    //执行操作更新数据
    

    //end   执行操作更新数据
    if (token != null)
    {
    eventAggregatorEx.GetEvent<UserChangedEvent>().Unsubscribe(UserChanged);
    }
  }

}

 

wpf viewmodel之间的通信

标签:

原文地址:http://www.cnblogs.com/azdjdgh/p/4460724.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!