0

I am making a WPF application with the design pattern MVVM, in my next step i need to use the content of a DataGrid,shown in MainWindow, in another Window. Is there a way to use items created in a specific Window in other Windows passing by ViewModels ?

Ahmed Attia
  • 127
  • 1
  • 10

1 Answers1

1

You can pass the MainViewModel as a reference to your other view models. That way you can access the data from the MainViewModel from your other view models.

 public class MainViewModel
{
    public AnotherViewModel avm { get; set; }
    public int ImportantInfo { get; set; }
    public MainViewModel()
    {
        avm = new AnotherViewModel(this);
    }
}

public class AnotherViewModel
{
    public MainViewModel mvm { get; set; }
    public AnotherViewModel(MainViewModel mvm)
    {
        this.mvm = mvm;
        MoreImportantINfo = this.mvm.ImportantInfo;
    }
    public int MoreImportantINfo { get; set; }      
}

This type of reference is just an example that could be used in a smaller project. For larger projects this same idea is implemented through dependency injection (DI). Check out this post tor read more on DI here

Another approach is to use events. Have the any Viewmodel that wants data from the MainViewModel subscribe to an event that the MainViewModel invokes with the desired data.

Community
  • 1
  • 1
mrsargent
  • 2,267
  • 3
  • 19
  • 36
  • Isn't a better to design to either use dependency injection, or messaging via an event aggregator or better yet have shared content in a service. – TYY Jan 21 '16 at 15:25
  • yes it is better to use DI unless it is a smaller project. I was just giving a basic example of how to share resources. – mrsargent Jan 21 '16 at 15:26