简体   繁体   中英

How to store the loaded View, so that we don't need to Initialize the component again when we reach to the same View

Actually I am having two buttons. When I click first button then one UserControl will be visible in ContentControl, and when I click on second button then another UserControl will come and sit in ContentControl. The problem is, everytime when I click buttons it will load particular UserControl->InitializeComponent() method. I want to load the View only one time in the beginning and not everytime when I switch from one UserControl to another. A lot of Thanks!

You have several options.

A dictionary would be one.

 Dictionary<Type, UserControl> MyControls

You can check if you have an instance already:

 MyControls.ContainsKey(TypeOfUserControl);

And use the one you already have or new up an instance if there's none there. And of course add to the dictionary.

This dictionary could be held in a dependency injection container or be a static so you can reference it from wherever you like. Or maybe all the usercontrols you care about are instantiated in one place.

You could alternatively use dependency injection and make all your usercontrols singletons.

The exact syntax depending on which DI container you use but for the microsoft one:

  services.AddSingleton<YourUserControl>();

If this was particularly problematic ( for reasons I can't imagine ) then you could perhaps use the Lazy instantiation pattern to make your usercontrols effectively statics.

https://csharpindepth.com/articles/singleton#lazy

Or maybe this is literally two usercontrols in one piece of code and you could simply cache in two private variables.

NOTE:

I wonder what you're doing in the initialisation.

A common pattern is viewmodel first where a viewmodel instance would be presented to a view and templated into UI. In this case initialisation logic would be in that viewmodel. That approach perhaps just changes the type of thing you're caching in the dictionary or dependency injection container.

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