加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

wpf – 使用WindowManager重新激活退出窗口

发布时间:2020-12-14 03:58:51 所属栏目:Windows 来源:网络整理
导读:我正在使用 WPF和当前最新版本的Caliburn.Micro(1.4.1).我使用 IWindowManager.ShowWindow(…)打开一个新的无模式窗口: private void OpenOrReactivateInfoView(){ if(this.infoViewModel == null) { this.infoViewModel = new InfoViewModel(); } this.win
我正在使用 WPF和当前最新版本的Caliburn.Micro(1.4.1).我使用 IWindowManager.ShowWindow(…)打开一个新的无模式窗口:

private void OpenOrReactivateInfoView()
{
    if(this.infoViewModel == null)
    {
        this.infoViewModel = new InfoViewModel();
    }

    this.windowManager.ShowWindow(this.infoViewModel);
}

每次调用OpenOrReactivateInfoView()时,我都不想打开一个新窗口,而是想检查窗口是否仍然打开,如果是,则现有窗口应该重新获得焦点.

我们将成为一名优秀的Calibrun.Micro方式来解决这个问题?我确实希望避免在viewmodel中保留对窗口(或任何UIElement)的引用.另请注意,这是许多无模式对话框的常见行为,因此最好以通用的可重用方式解决此问题.

Caliburn.Micro是否已经拥有内置的手段?

解决方法

一种相当直接的方法来实际跟踪你的窗口
必须实现IViewAware将保留弱引用的字典
到您的ViewModel和Views一起检查,然后检查您是否已经
是否有现有的窗口.可以作为装饰器来实现
WindowManager,子类或扩展.

假设你没有,那么像下面这样简单的东西应该可以做到
实际上计划打开足够的窗户甚至死亡的WeakReferences
会影响表现.如果它将长期运行它不应该
很难实现某种清理.

public class MyFancyWindowManager : WindowManager
{
    IDictionary<WeakReference,WeakReference> windows = new Dictionary<WeakReference,WeakReference>();

    public override void ShowWindow(object rootModel,object context = null,IDictionary<string,object> settings = null)
    {
        NavigationWindow navWindow = null;

        if (Application.Current != null && Application.Current.MainWindow != null)
        {
            navWindow = Application.Current.MainWindow as NavigationWindow;
        }

        if (navWindow != null)
        {
            var window = CreatePage(rootModel,context,settings);
            navWindow.Navigate(window);
        }
        else
        {
            var window = GetExistingWindow(rootModel);
            if (window == null)
            {
                window = CreateWindow(rootModel,false,settings);
                windows.Add(new WeakReference(rootModel),new WeakReference(window));
                window.Show();
            }
            else
            {
                window.Focus();
            }
        }

    }

    protected virtual Window GetExistingWindow(object model)
    {
        if(!windows.Any(d => d.Key.IsAlive && d.Key.Target == model))
            return null;

        var existingWindow = windows.Single(d => d.Key.Target == model).Value;
        return existingWindow.IsAlive ? existingWindow.Target as Window : null;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读