简体   繁体   中英

How to instantiate View from ViewModel even if I don't want to display it right after?

I want to search through a few views' controls but I only have access to their ViewModels, because these views aren't displayed and there is no living instance of the view. Is there a way to instantiate a View through its ViewModel in code? I have to instantiate several of them in one place, having only the VM type. I'd like the code to be generic.

Edit - more specific information: I have a lot of different settings views. I want to search through them because right now, the user has to search manually - meaning the user has to go to every tab and look for the word he needs. My VM is, of course, taking data from inputs but I am not interested in data - I'm interested in labels and texts which are shown to the user.

I'm using WPF, MVVM and Caliburn.Micro.

Yes you can do it. u need to understand that the views are also a class so u just need to create an object like any other class and when u call the ShowDialog. the method in view call it will display on UI

View MyView= new View();
ViewModel MyViewmodel= new ViewModel();
MyView.DataContext=MyViewmodel;

In this part of code it will create object of View and ViewModel and assign the dataContext Prop to Your Vm but not Displayed Any where.

List<View> AllView= new List<View>()
AllView.Add(MyView);

Here I saved your view in list. and these can be static or global. and whenever I need to access these, I will do

AllView[0].ShowDialog();

I'm displaying the first view. I think u got the idea. as per generic method u can check it create an object. it's not that hard. as per me it's not necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM