C# 切换窗口可见性将实例化新窗口

C# 切换窗口可见性将实例化新窗口,c#,wpf,prism,C#,Wpf,Prism,我有一个带Prism的模块化应用程序。将显示一个简单的窗口(外壳)。shell包含一个任务栏图标,该图标调用一个命令来切换windows可见性。单击TaskbarIcon将创建my shell的新实例,而不是切换原始实例的可见性。有人知道为什么我的代码没有在第一个shell上调用该方法吗 我的引导程序 protected override DependencyObject CreateShell() { var shell = ServiceLocator.Curren

我有一个带Prism的模块化应用程序。将显示一个简单的窗口(外壳)。shell包含一个任务栏图标,该图标调用一个命令来切换windows可见性。单击TaskbarIcon将创建my shell的新实例,而不是切换原始实例的可见性。有人知道为什么我的代码没有在第一个shell上调用该方法吗

我的引导程序

 protected override DependencyObject CreateShell()
    {
        var shell = ServiceLocator.Current.GetInstance<Shell>();
        RegisterTypeIfMissing(typeof(Shell), typeof(Shell), true);
        return shell;

    }

    protected override void InitializeShell()
    {

        var mainWindow = (Shell)this.Shell;
        var regionManager = ServiceLocator.Current.GetInstance<IRegionManager>();
        Application.Current.MainWindow = mainWindow;
        mainWindow.Show();
}

您并不总是使用单例shell


CreateShell
中,首先获得一个shell实例,然后将shell注册为singleton。稍后,在
ShowWindowCommand.Execute
中,您将获得一个单例实例,它与您之前解析的非单例实例不同。容器如何知道第一个解析的实例稍后将用作单例?您甚至可能在注册为singleton之前解析了多个实例…

我现在在命令类中使用“((Shell)Application.Current.MainWindow).toggleVisibility();”。它的工作方式很有魅力,但是我想知道第一种方法的错误。你是对的,在将另一个注册为singleton之前创建一个shell实例毫无意义。。。我已经删除了“var shell=…”语句,并在注册它之后返回ServiceLocator.Current.GetInstance()。现在它起作用了。非常感谢。
<tb:TaskbarIcon
            Name="ToolbarIcon"
          IconSource="/Resources/images/icon.ico"
          ToolTipText="Some text" 
            LeftClickCommand="{StaticResource ShowWindowCommand}"/>
    public class ShowWindowCommand : ICommand
{
    public void Execute(object parameter)
    {
        ServiceLocator.Current.GetInstance<Shell>().toggleVisibility();
    }

    public bool CanExecute(object parameter)
    {
        return true;
    }
    public event EventHandler CanExecuteChanged;
} 
public void toggleVisibility()
    {
        if (this.Visibility == System.Windows.Visibility.Visible){
            this.Visibility = System.Windows.Visibility.Collapsed;                
        }
        else
        {
            this.Visibility = System.Windows.Visibility.Visible;

        }  
    }