繁体   English   中英

Caliburn.Micro视图未在弹出窗口中销毁

[英]Caliburn.Micro view not destroyed in Popup

当我关闭用Caliburn micro创建的弹出窗口时,我遇到了一个问题:该视图似乎没有被破坏。

我将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次打开/关闭之后,我对ViewModel中的get Message进行了5次调用。

因此,我收到了旧视图的绑定:

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); } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM