c# - How to avoid the View being disposed -


i'm using contentcontrol im wpf application show different views user.

<contentcontrol content="{binding currentpageviewmodel}"/> 

by pushing button user can switch value of currentpageviewmodel viewmodel object and, of datatemplate, switch view.

<datatemplate datatype="{x:type viewmodel:administrationviewmodel}">     <view:administrationview /> </datatemplate> <datatemplate datatype="{x:type viewmodel:healthviewmodel}">     <view:healthview /> </datatemplate> 

so far good.


my problem starts whenever view switched. old view discarded , framework deletes/disposes view object.

grid sort settings therefore lost , what's worse, of views values set null. null values propagated viewmodel databinding, totaly messes viewmodel data!

how can prevent view object deleted/discarded?

simplest powerfull solution control views' life using converter instead of datatemplates:

<contentcontrol  content="{binding currentpageviewmodel, converter={staticresource viewmodeltoviewconverter}"/> 
public class viewmodeltoviewconverter: ivalueconverter {     public object convert(object value, type targettype, object parameter, cultureinfo culture)     {         if (value == null) return null;         //use naming convention or custom settings here view type         var viewmodeltype = value.gettype();         var viewtype = ...           var view = (frameworkelement) yourioccontainer.resolve(viewtype);         view.datacontext = value;         return view;     }     ...  } 

you need setup ioc particular view's return singleton instance. ioc allows dependency injecion views. instead of ioc may use own factory pattern implementation.

however, viewmodel properties should not messed, when view disconnected visual three. there's issue in bindings , should open new question this


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -