1

I have MVVM, where VM is in separate ClassLibrary project. I need to implement closing window. All solutions that I see involve passing window directly. The problem is that Class Library doesn't know System.Windows.Window type so, even though I can pass the form as object I cannot call a Close method on it.

What should I do? Is there a solution, specific for Class Libraries?

mm8
  • 163,881
  • 10
  • 57
  • 88
anjulis
  • 219
  • 1
  • 4
  • 14
  • Can you pass an event? Delegate? – Gilad Aug 13 '18 at 20:35
  • Possible duplicate of [Closing Child Window from ViewModel](https://stackoverflow.com/questions/43294156/closing-child-window-from-viewmodel) – Brandon Hood Aug 14 '18 at 01:09
  • Possible duplicate of [How should the ViewModel close the form?](https://stackoverflow.com/questions/501886/how-should-the-viewmodel-close-the-form) – Peregrine Aug 14 '18 at 01:26
  • May be you can use `Application.Current.MainWindow.Close();` in PCL. Give it a try. – Gaurang Dave Aug 14 '18 at 02:29
  • Also check this : https://social.msdn.microsoft.com/Forums/vstudio/en-US/d10de84c-bef1-46ed-8127-7ad19b8eec37/using-a-wpf-window-in-a-class-library-project?forum=wpf – Gaurang Dave Aug 14 '18 at 02:33

1 Answers1

2

One solution would be to define an interface in the class library where the view models are defined:

public interface IWindow
{
    void Close();
}

Implement this interface in your window classes in the WPF application:

public partial class MainWindow : Window, IWindow { ... }

You can pass an IWindow reference to the view model instead of passing a System.Windows.Window reference. Then the view model knows only about an interface that can be easily mocked out in an unit test.

You may also want to consider using a window service to open and close windows. Please refer to my answer to the following question for an example:

MVVM show new window from VM when seperated projects

mm8
  • 163,881
  • 10
  • 57
  • 88