0

My application consists of a single window with various view models displaying graphs/charts/tables, etc. My users have decided they want the ability to pop out a chart and have it display in its own window, similar to how you can drag a tab out of Chrome, or a docked view out of Visual Studio, to see it in its own window.

I would like to avoid generating a new instance of the view model for use in the new window.

Is there a way to preserve the view model while moving it from one window to another? And is there a way to easily remove the corresponding view from one visual tree and add it to another?

UPDATE:

I looked into AvalonDock and it's not quite what I'm looking for. I just want to move an existing viewmodel from one part of the UI to a window. Any ideas?

NielW
  • 3,626
  • 1
  • 30
  • 38

1 Answers1

0

I would like to avoid generating a new instance of the view model for use in the new window.

I wonder why is that so? Anyways, you can achieve it this way:

// App.xaml.cs
public static MainViewModel MainVM {
    get {
        // create and return main view model once
    }
}

// Classes
public class MainViewModel {

    private ViewModel1 vm1;
    public ViewModel1 VM1 {
        get {
            return vm1;
        }
    }

    public void InitializeViewModel1() {
        ...
    }
}

public class ViewModel1 {
    ...
}

Although this will work in your case, I suggest you read about having static or single instance of viewmodels and decide if that's the approach you still want to follow.

Nikhil Vartak
  • 5,002
  • 3
  • 26
  • 32
  • Thank you for your answer, but it doesn't answer the question. I'm already doing this. The problem is that WPF doesn't like to have a view model in the visual tree multiple times. It doesn't quite generate all the view components properly. I've seen some pretty weird stuff in my 3+ years with WPF. – NielW Sep 10 '15 at 14:32
  • I don't want to generate a new instance of the view model because then I'd have to save all of the user's changes out, so I could regenerate it in the exact state it was already in. In VS they don't kill your VM before regenerating it in the new window. They just move it. – NielW Sep 10 '15 at 14:33