Caliburn.Micro view在Popup中未被破坏

本文关键字:Popup Micro view Caliburn | 更新日期: 2023-09-27 18:33:51

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

我将Caliburn.Micro 2.0.1与MEF一起使用,您可以在此处查看我的示例:https://github.com/louisfish/BaseCaliburn

基本上,我创建了一个内部带有按钮的窗口。当您单击此按钮时,将打开一个新窗口,其中包含窗口管理器的显示窗口功能。在此弹出窗口中,我创建了一个带有绑定的消息。当我的消息进入我的视图模型时,我会放置输出跟踪。

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

Caliburn.Micro view在Popup中未被破坏

  • 您有一个 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);
    }