How to pass parameters from parent module to my ViewModel?

I have a "open" command in which the user can select a file. When the file is selected (and therefore I have the file path as a string ), I get a new instance of my DataView (with NonShared and CreationPolicy attributes) from the CompositionContainer and display it in a specific region. My DataView gets its DataViewModel through DI. Now my problem is how to pass the selected path to the NEW file (created after the file is selected) ViewModel?

My first approach seemed smart and worked until I created only one View . But since I create several views (tabs), the following approach does NOT work, because I cannot compose the same value more than once.

 if (fileDialog.ShowDialog() == true) { Container.ComposeExportedValue("FilePath", fileDialog.FileName); IRegion contentRegion = regionManager.Regions[Regions.CONTENT]; contentRegion.Add(Container.GetExportedValue<IDataView>(), null, true); } [ImportingConstructor] public DataViewModel(IRegionManager regionManager, [Import("FilePath")] string filePath) { } 

Is there any other way to insert / pass my string parameter in viewmodel?

+4
source share
2 answers

I think you need to use the service to open files, and not export the values ​​through MEF.

If you had a shared service that all your ViewModels used, they could just import your service and call the OpenFile () method.

I have an open source MVVM project that has a quick example of this. See sample templates here .

Also check the top answer here , they have another implementation.

+1
source

I always did such things in ViewModel

My ParentViewModel will contain an instance of OpenFileViewModel , and when ParentViewModel.SelectFileCommand is executed, it calls something like OpenFileViewModel.SelectFile()

To get the selected file, I often subscribe to OpenFileViewModel.PropertyChanged and listen to the change events in the FileName property, or sometimes I will have a rewritable ProcessFile method that I can connect to the event that fires when a file is selected.

The OpenFileViewModel.SelectFile method usually looks something like this:

 private void SelectFile() { var dlg = new OpenFileDialog(); dlg.DefaultExt = this.Extension; dlg.Filter = this.Filter; if (dlg.ShowDialog() == true) { var file = new FileInfo(dlg.FileName); FileName = file.FullName; if (ProcessFileDelegate != null) ProcessFileDelegate() } } 

and my ParentViewModel will often contain code that looks something like this:

 public ParentViewModel() { this.OpenFileDialog = new OpenFileViewModel(); this.OpenFileDialog.PropertyChanged += OpenFileDialog_PropertyChanged; this.OpenFileDialog.ProcessFileDelegate = ProcessFile; } 
+1
source

Source: https://habr.com/ru/post/1369325/


All Articles