Rakr Rakr - 1 year ago 106
C# Question

Switch views in same Window WPF without creating new instances of the pages

MY application has 3 pages (one MainWindow and 2 pages where simple selections are made).

Currently i use the following navigation structure to switch between the pages http://azerdark.wordpress.com/2010/04/23/multi-page-application-in-wpf/.
It basically uses a interface to pass the reference of a page and creates new instances.

The idea is i can only have 1 window open at one time. For example when i navigate from Page A to B, B replaces the content of A. The order is Always A -> B -> C -> A (back to main Window) or A -> B -> A.

All the content gets displayed in 1 window at all times in other words.
With my current solution i have the problem that i instantiate a new instance of the page every time it switches (for example A -> B -> A has 2x New PageA() as result.

This on its turn results in having to use a lot of static methods and classes which i do not really like.

Is there a better solution for this that does not require a entire overhaul of my current application navigation structure?

In my current solution i use a static ObversableCollection list to remember a number of controls that get dynamically created so when i go back to page A (mainWindow) everything remains the same.

Thanks in advance.

Answer Source

I don't really understand why would you use navigation in such a simple settings (3 pages and fixed navigation structure). Much easier way would be:

  1. Use MainWindow as content placeholder
  2. Create UserControls as pages
  3. Define static class to hold pages in distinct properties. Initialize them if need be (singleton instances).
  4. Use MainWindow.SetPage(Pages.First) to change pages.

In code, this would pretty much look like this:

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
            if (_first == null) 
                _first =  new FirstUserControl();
            return _first;
    // ...

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


Though if you really need the navigation, you could use just the static part of it and pass the singletoned instances to your SwitchPage method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download