0

I'm working on a WPF app using prism (MVVM), and I'd like to create a View for print, which will not be displayed on GUI.
My current code is shown below, but I'd like to avoid directly instantiating a View via its constructor.

void ExecutePrint()
{
    var vm = new CustomViewModel();
    var view = new CustomView { DataContext = vm }; // ← I'd like to avoid this!
    vm.Print();
}

How can I link a View with a ViewModle in a case like this using prism?

NOTE:

  1. In the code above, CustomViewModel is instantiated every time the ExecutePrint method is called. Therefore, CustomViewModel can not be registered as a singleton.
  2. The instance of CustomView is used only for print. It should never be displayed on GUI.
  3. In the code above, vm.Print() perfectly works. CustomViewModel can print the instance of CustomView via Behavior. All I want to do is to complete vm.Print() without directly instantiating CustomView.
user4134476
  • 385
  • 4
  • 22
  • Does this answer your question? [Prism pop-up new window in WPF](https://stackoverflow.com/questions/34125982/prism-pop-up-new-window-in-wpf) – Hank Mar 16 '23 at 15:46
  • In the above article, it seems that pop-up window is actually displayed on GUI, judging from the code ‘IsModal = true’. I’d like to resolve my problem without displaying the print target view on GUI. – user4134476 Mar 17 '23 at 03:28
  • 1
    Clarify what you mean by "without displaying the print target view on GUI". In the sample code you aren't using `view` so why instantiate it? Unless it's doing some sort of side effect logic in its constructor. – Hank Mar 17 '23 at 04:04
  • If you need the view to print it, what's wrong with creating it to print it? Why do you want to avoid creating it? – Haukinger Mar 17 '23 at 10:35
  • @Hank I'm using `view` to print it because it is referenced by `vm` via `Behavior`. What I'm aiming to to is something like the following: `var vm = new CustomViewModel();` // view is automatically instantiated somewhere by prism. `vm.Print();` – user4134476 Mar 26 '23 at 05:56

0 Answers0