2012-04-17 130 views
2

我的應用程序有3個頁面(一個MainWindow和2個頁面,在這些頁面中進行簡單的選擇)。在同一個窗口WPF中切換視圖而不創建頁面的新實例

當前我使用以下導航結構在頁面http://azerdark.wordpress.com/2010/04/23/multi-page-application-in-wpf/之間切換。 它基本上使用一個接口來傳遞一個頁面的引用並創建新的實例。

這個想法是我一次只能打開1個窗口。例如,當我從頁面A導航到B時,B將替換A的內容。訂單始終爲A→B→C→A(返回主窗口)或A→B→A。

換句話說,所有內容都會一直顯示在1個窗口中。 使用我當前的解決方案,我遇到了問題,我每次切換時都會實例化頁面的一個新實例(例如A→B→A具有2x New PageA()作爲結果)

在必須使用大量的靜態方法和類的,我真的不喜歡。

是否有這更好的解決方案,不要求我的當前應用程序的導航結構的整個大修?

在我目前的解決方案我使用一個靜態的ObversableCollection列表來記住一些動態創建的控件,所以當我回到頁面A(mainWindow)時,一切都保持不變。

在此先感謝。

+1

我可能是錯的,但是當'this.Content = nextPage;'被執行時不會使當前頁面超出範圍並被垃圾收集器清除,因此實際上不會有同一頁面的多個實例。您使用的解決方案對我來說似乎相當不錯 – 2012-04-17 18:16:40

回答

5

我不明白你爲什麼要在這樣一個簡單的設置(3頁和固定導航結構)中使用導航。更簡單的方法是:

  1. 使用主窗口的內容佔位符
  2. 創建用戶控件的頁面
  3. 定義靜態類持有不同的屬性頁面。如果需要,初始化它們(單例實例)。
  4. 使用MainWindow.SetPage(Pages.First)更改頁面。

在代碼中,這將幾乎是這樣的:

public class MainWindow : Window 
{ 
    // ... 
    public void SetPage(UserControl page) 
    { 
     this.Content = page; 
    } 
} 

// ... 

public static class Pages 
{ 
    private FirstUserControl _first; 
    private SecondUserControl _second; 
    private ThirdUserControl _third; 
    private MainWindow _window = Application.Current.MainWindow; 

    public UserControl First 
    { 
     get 
     { 
      if (_first == null) 
       _first = new FirstUserControl(); 
      return _first; 
     } 
    } 
    // ... 
} 

// Somewhere in B (after A -> B) 

    MainWindow.SetPage(Pages.First); 

但如果你真的需要導航,你可以只使用它的靜態部分,並通過singletoned實例您SwitchPage方法。

+0

Ty爲答覆,我是否應該改變它呢? 對於一個小的導航,使更有意義idd :) – Rakr 2012-04-17 18:36:19

+0

這取決於。你應該權衡兩種方法的優缺點。 – 2012-04-17 18:37:52

+0

你用'A'和'B'指的是什麼? – 2016-02-18 15:42:15

1
public partial class MainWindow : Window 
{ 

    string un; 
    string pw; 

    public MainWindow() 
    { 
     InitializeComponent(); 
    } 

    private void Button_Click_1(object sender, RoutedEventArgs e) 
    { 

     un = txtName.Text; 
     pw = txtPw.Text; 

     if (un.Equals("steve") && pw.Equals ("cool")) 
     { 
      Home h= new Home(); 
      this.Content = h.Content; ***// this is where we change the window's contents*** 


     } 
    } 
} 
相關問題