2011-07-10 31 views
1

我對Caliburn Micro很新,想在OnExit期間訪問ViewModel屬性。從引導程序訪問MainViewModel

public class AppBootstrapper : Bootstrapper<MainViewModel> 
{ 
    protected override void OnExit(object sender, EventArgs e) 
    { 
     if (mainViewModel.MyParam == 42) 
     { 

     } 
     base.OnExit(sender, e); 
    } 

從默認模板WP7(不卡利)我已經習慣了有App.ViewModel,這是一個單身獲得訪問,那裏的視圖模型將在第一次訪問創建一個靜態字段。 (請參見下面的代碼片段)

public partial class App : Application 
{ 
    private static MainViewModel viewModel = null; 

    public static MainViewModel ViewModel 
    { 
     get 
     { 
      // Delay creation of the view model until necessary 
      if (viewModel == null) 
       viewModel = new MainViewModel(); 

      return viewModel; 
     } 
     set 
     { 
      viewModel = value; 
     } 
    } 

現在,我嘗試使用微卡利1.1與WPF項目,不知道如何應該這樣做。 我需要在AppBootStrapper內的OnExit期間訪問ViewModel。

我想,這應該是可能的,因爲我的AppBootstrapper是從引導程序繼承,但不能找到這樣做的正確的方式..

任何提示,這可怎麼在WPF來完成是非常歡迎?

感謝 羅布

+0

我假設Caliburn.Micro,因爲你提到WP7(如果沒有,請更正)。什麼版本的框架? –

+0

你是如何在WP7中完成的?在'App.ViewModel'中,'App'是什麼? –

+0

嗨,喬爾,對不起我的問題確切。在WP7中,我使用了默認模板。我的問題是基於CM 1.1的WPF版本。剛剛更新了我的問題!謝謝! – Rob

回答

0

嘗試

MainViewModel mainViewModel = IoC.Get<MainViewModel>(); 

這裏是它會怎樣看你的代碼:

public class AppBootstrapper : Bootstrapper<MainViewModel> 
{ 
    protected override void OnExit(object sender, EventArgs e) 
    { 
     // Get the Main View Model 
     MainViewModel mainViewModel = IoC.Get<MainViewModel>(); 
     if (mainViewModel.MyParam == 42) 
     { 
      //Do work 
     } 
     base.OnExit(sender, e); 
    } 
} 

這是假設兩件事情:

  1. 你MainViewModel類是前移植typeof(MainViewModel)並沒有什麼不同,例如typeof(IShell)
  2. 您正在使用C.M的默認MEF實現。
+0

是的,你是假設是絕對正確的,雖然我以前不知道這一點。隨着你的提示,我可以到達MainViewmodel,但現在它總是創建一個新的實例。我應該使用什麼樣的模式來獲得我的viewmodel的唯一實例。我必須自己實施一些單身模式,還是可以在這裏幫助我? 非常感謝您的幫助! – Rob

+0

IoC shoud只創建一個新實例,然後在進一步請求MainViewModel時向您發送同一實例的副本。 問題 - 你手動intanciate你的MainViewModel,還是你讓Caliburn.Micro爲你做? 實質上,IoC靜態類應該處理與使用單例容器相同的東西,但是它比該鏈接中的Container解決方案「重」得多。樂意效勞! – EtherDragon

0

搜索一點點經過我想我已經找到了解決辦法,以我自己的問題:增加SimpleContainer.cs從這裏:link

,並將此我AppBootstrapper代碼:

public class AppBootstrapper : Bootstrapper<MainViewModel> 
{ 

    private SimpleContainer container; 

    protected override void Configure() 
    { 
    container = new SimpleContainer(); 
    container.RegisterSingleton(typeof(MainViewModel), null, typeof(MainViewModel)); 
    container.RegisterSingleton(typeof(IWindowManager), null, typeof(WindowManager)); 
    } 

    protected override object GetInstance(Type service, string key) 
    { 
    return container.GetInstance(service, key); 
    } 

很高興聽到一些評論,無論這是否好。