2014-12-10 76 views
1

我關閉用Caliburn micro創建的彈出窗口時遇到了問題:視圖似乎不被銷燬。Caliburn.Micro視圖在Popup中不被破壞

我用Caliburn.Micro 2.0.1 MEF的,你可以在這裏看到我爲例: https://github.com/louisfish/BaseCaliburn

基本上,我創建了一個窗口,裏面的按鈕。 當你點擊這個按鈕時,用WindowManager的ShowWindow函數打開一個新窗口。 在這個彈出窗口中,我創建了一個帶有綁定的消息。 當我的消息進入ViewModel時,我輸出了跟蹤信息。

using Caliburn.Micro; 
using System; 
using System.Collections.Generic; 
using System.ComponentModel.Composition; 
using System.Diagnostics; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace BaseCaliburn.ViewModels 
{ 
    [Export] 
    public class PopupViewModel : Screen 
    { 
     private int _timesOpened; 
     private string _message; 
     public string Message 
     { 
      get 
      { 
       Debug.WriteLine("Message is get"); 
       return _message; 
      } 
      set 
      { 
       if (value == _message) return; 
       _message = value; 
       NotifyOfPropertyChange(() => Message); 
      } 
     } 
     protected override void OnActivate() 
     { 
      Debug.WriteLine("---Window is activated---"); 
      _timesOpened++; 

      Message = "Popup number : " + _timesOpened; 
     }  
    } 
} 

每次我打開和關閉窗口時,舊的綁定都會停留在那裏。 所以5打開/關閉後,我有5調用我的ViewModel中的消息。

所以我收到的舊觀點的結合:

Message is get 
---Window is activated--- 
Message is get 
Message is get 
Message is get 
Message is get 
Message is get 
+0

兩件事情可能,1)你是不是在你的popupview關閉調用TryClose(真),這應該關閉視圖模型和「殺它「,因爲你正在使用MEF,有'''[PartCreationPolicy(CreationPolicy.NonShared)''',默認情況下,MEF用PartCreationPolicy = Shared創建所有部分,相當於」Singleton「 – mvermef 2014-12-11 09:20:39

+0

我嘗試添加[PartCreationPolicy(CreationPolicy .NonShared)]到我的PopupViewModel和行爲是相同的。 – 2014-12-11 13:58:07

回答

1
  • 你有HomeViewModel一個單一實例。您將主窗口綁定到HomeViewModel,因此每次單擊StartApp時,都會在同一實例上調用該方法。
  • 此實例具有PopupViewModel屬性,只要創建了HomeViewModel,該屬性就由您的依賴注入容器初始化。然後,它保持不變。每當您的StartApp方法獲取該屬性的值時,都會返回PopupViewModel的同一個實例。
  • 您實際上想要的是每次撥打StartApp時新增的PopupViewModel實例。你需要一個工廠。在MEF,您可以導入ExportFactory<T>按需創建實例:

    [Import] 
    public ExportFactory<PopupViewModel> PopupViewModelFactory { get; set; } 
    
    public void StartApp() 
    { 
        Application.Current.ShutdownMode = ShutdownMode.OnMainWindowClose; 
    
        PopupViewModel newPopup = this.PopupViewModelFactory.CreateExport().Value; 
        IoC.Get<IWindowManager>().ShowWindow(newPopup); 
    } 
    
+0

是的,謝謝它的作品。 – 2014-12-11 19:50:10