-1
\$\begingroup\$

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; }

    }
\$\endgroup\$
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – t3chb0t Jun 22 '19 at 5:25
1
\$\begingroup\$

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.

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.