【问题标题】:Display WPF Window in Place of Another Without Show/Close显示 WPF 窗口代替另一个不显示/关闭
【发布时间】:2014-08-06 18:35:31
【问题描述】:

我有几个 WPF 窗口,我的项目通过调用 windowA.Close() 和 windowB.Show() 在它们之间切换。我需要在没有任何过渡的情况下进行更改(即一个窗口关闭和另一个打开的动画)。当然,我可以用多个窗口的功能制作一个非常混乱的窗口,但是有没有更简单的方法来做到这一点?

【问题讨论】:

  • 使用NavigationWindowTabControl 比使用多个窗口更自然吗?
  • 一次只能显示一个窗口,所以我不这么认为。你认为我还应该使用其中一种吗?

标签: c# wpf window


【解决方案1】:

MVVM 模式是一种很好的方法。您可以将单个外部 Window 制作为一个外壳,该外壳可以换入和换出代表 windowA 和 windowB 功能的 UserControl。实现 MVVM 的答案有点多; here 是一个基本实现的好主意,对于您想要做的事情来说已经足够了。

假设:

1) 您正在实施 MVVM,并且

2) 您的主“shell”窗口有一个视图模型和 Window,“子窗口”有一个视图模型和 UserControl。

无论如何,在主窗口的视图模型中,您需要为子视图的视图模型设置一个属性,如下所示:

 private object currentView;
 public object CurrentView
 {
     get{ return this.currentView;}
     set 
     { 
          this.currentView = value;
          RaisePropertyChanged("CurrentView"); //assumes you've implemented an MVVM pattern with a method to notify the view when a property has changed like the link above
     }     

然后在 XAML 中,为每个子视图添加数据模板:

这就是说,“如果此视图中的某些内容绑定了一个值为 WindowAViewModel 的属性,则在其位置显示 WindowAView。”

然后您将 ContentControl 绑定到 CurrentView 属性:

<ContentControl Content="{Binding CurrentView}"/>

最后,在您的主窗口视图模型代码中,当您想要切换到 A 或 B 视图时,您只需执行以下操作:

 this.CurrentView = new WindowAViewModel(); //along with whatever initialization needs to occur

由于该属性设置为在更改时通知,它会通知视图 CurrentView 中有新内容,并且 DataTemplates 告诉主窗口要为新内容呈现什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-06
    • 1970-01-01
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多