# Is attempt like this, when using Application class, breaking MVVM pattern? [closed]

In my application I am using two view models. MainViewModel if fiered when MianWindow is initialized. And UpdateViewModel is fiered when UpdateWindow is initialized.

The update VM is supposed to use data from collection that is a property of the main VM and has its instance aready, and I need to refer to it somehow. And I was wondering, is refering to this collection with MainViewModel vm = (MainViewModel)win.DataContext; is breaking MVVM pattern or testability somehow or is any kind of antipattern? Or maybe the collections has to be passed update VM as a parameters, and sent back? Thank you.

The code:

public class UpdateViewModel : ViewModelBase
{
public UpdateViewModel()
{
Jockeys = new ObservableCollection<LoadedJockey>();

PopulateCollections();
}

private void PopulateCollections()
{
MainWindow win = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
MainViewModel vm = (MainViewModel)win.DataContext;

Jockeys = vm.Jockeys; //is it ok?

vm.Jockeys //is it ok?
}

public ObservableCollection<LoadedJockey> Jockeys { get; private set; }

}

• We need more context than this. What are MainWindow and MainViewModel? How does you xaml look like? What is this code doing at all? Is this a new window, a popup, a user-control, etc, etc... Currently, this is too general. – t3chb0t Jun 22 '19 at 5:25

## 1 Answer

MainWindow is a view object which should be avoided in ViewModel classes. Passing the collection as constructor parameter to the UpdateViewModel would be better. If you want to achieve a high level of testability, you would need to study more about dependency injection.

• Thank you, that is what I was suspecting, that it could be too tight coupling. Right now I started to learn about ViewModel navigation. – bakunet Jun 22 '19 at 7:08