首页 > 解决方案 > 从屏幕关闭导体窗口

问题描述

我有一个名为 WindowViewModel 的 ViewModel,它继承自Conductor<IScreen>.Collection.OneActive. 从这个 ViewModel,我打开 ChildView(带有WindowManager.ShowWindow(ChildViewModelInstance))。我想要做的是从 ChildViewModel 关闭 WindowView。

这是我的 WindowViewModel:

public class WindowViewModel : Conductor<IScreen>.Collection.OneActive,  IHandle<bool>
{
    public WindowViewModel()
    {

    }

    public void OpenChildView()
    { 
       //some code
    } 

    public void CloseItem(Screen item)
    {
        item.TryClose();
        if (Items.Count == 0)
            TryClose();
    }

    public void Handle(bool message)
    {
       //for some reason this isn't handled
       TryClose();
    }
}

这是我的 ChildViewModel:

public class ChildViewModel : Screen
{
    public ChildViewModel()
    {
      //getting eventaggregator...
    }

    public void CloseWindow()
    {
       eventAgregator.PublishOnUIThread(true);
    }
}

ChildView是WindowView中tabcontrol的tabItem。当我按下x特定的 tabItem 标题时(如果只有一个 tabitem),WindowView 将关闭(因为调用了 closeitem)。

我试过PublishOnCurrentThreadandPublishOnbackgroundThread而不是PublishOnUIThread,但它们也不起作用。

标签: wpfcaliburn.micro

解决方案


通过调用它的 Subscribe 方法注入WindowViewModelIEventAggregator订阅它:

public class WindowViewModel : Conductor<IScreen>.Collection.OneActive, IHandle<bool>
{
    private readonly IEventAggregator _eventAggregator;

    public MainViewModel(IEventAggregator eventAggregator)
    {
        _eventAggregator = eventAggregator;
        _eventAggregator.Subscribe(this);
    }

     public void Handle(bool message)
     {
         TryClose();
     }

     ...
}

推荐阅读