Caliburn.Micro视图在Popup中不被破坏
问题描述:
我关闭用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
答
- 你有
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
两件事情可能,1)你是不是在你的popupview关闭调用TryClose(真),这应该关闭视图模型和“杀它“,因为你正在使用MEF,有'''[PartCreationPolicy(CreationPolicy.NonShared)''',默认情况下,MEF用PartCreationPolicy = Shared创建所有部分,相当于”Singleton“ – mvermef 2014-12-11 09:20:39
我尝试添加[PartCreationPolicy(CreationPolicy .NonShared)]到我的PopupViewModel和行为是相同的。 – 2014-12-11 13:58:07