1

Is there some way to have a New Window which uses the same ViewModel as the MainWindow? The reason for this is that I have a data grid that I want to insert to, delete items, update, etc. But, when it comes to insertion I want to do it in a separate window, as in you click, open another window and insert from there. But as far as I've seen, it is not possible for two Views to use the same ViewWModel. Any ideas?

  • The same ViewModel-Type or the same Instance? – lokusking Jul 01 '16 at 07:24
  • 2
    A view model is just an object - you're just using a reference to the object, so there's no reason why not. That said you probably don't want to do this. At least look at a view model per row which *might* map to the insert view – Murph Jul 01 '16 at 07:27
  • Why this is downvoted and voted to close? It's a regular question related programming.... – Liero Jul 01 '16 at 07:34
  • If you're using MVVM I guess you already have the data layer separated. So it's probably not the ViewModel that you want to share, but the Model(s). Could you show how you currently create your new Window? – default Jul 01 '16 at 07:56
  • *But as far as I've seen, it is not possible for two Views to use the same ViewWModel.* What have you tried? Why is it not possible? – Bolu Jul 01 '16 at 09:04

2 Answers2

0

Technically it is totally possible and it is very easy to do. Lets say you have two windows Window1 and Window2.

you can have this code in Window1.xaml.cs:

void BtnOpenNewWindow_Click(object sender, EventArgs e)
{
   var window2= new Window2();
   window2.DataContext = this.DataContext;
   window2.Show();
}

or this code in Window1ViewModel.cs

void OpenNewWindowCommand_Execute()
{
   var window2= new Window2();
   window2.DataContext = this;
   window2.Show();
}

However, it's questionable whether it is good practice. There are better way how to share code or data between viewmodels. Actually it is not related to viewmodels only, they are general OOP principles.

To share code between viewmodels, you can use inheritance:

abstract CommonViewModel
Window1ViewModel extends CommonViewModel
Window2ViewModel extends CommonViewModel

as you can see, it keeps the 1:1 relationship between views and viewmodel.

To share data between viewmodels, you can reference single instance from different viewmodels

var common = new CommonDataOrLogic(); //this is usually model
var viewmodel1 = Window1ViewModel(common);
var viewmodel2 = Window2ViewModel(common);

And there are a lot of patterns you could use: Singleton, ServiceLocator, IoC, EventAggregator, etc..

Liero
  • 25,216
  • 29
  • 151
  • 297
-1

I hope,

If you set the owner of the new window as MainWindow means the new window can use the view model of the MainWindow.

For Example,

Window newWindow= new Window();
newWindow.Owner = App.Current.MainWindow;
Vinod Kumar
  • 408
  • 4
  • 18