Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A simple workaround is to set KeepAlive to true and then to ensure no issues with the VIewModel having bad state from a previous page load, the DataContext is set to a new instance each time in the Loaded event (i.e don't bind to an instance of the ViewModel in your Page.Resources dictionary for example as it will be persisted).</p> <p>A standard approach we use for binding the page to the view model is with a simple behavior attached to the page.</p> <pre><code>public sealed class PageViewModelBehavior : Behavior&lt;Page&gt; { public Type DataType { get; set; } protected override void OnAttached() { this.AssociatedObject.KeepAlive = true; this.AssociatedObject.Loaded += this.AssociatedObjectLoaded; this.AssociatedObject.Unloaded += this.AssociatedObjectUnloaded; base.OnAttached(); } protected override void OnDetaching() { this.AssociatedObject.Unloaded -= this.AssociatedObjectUnloaded; this.AssociatedObject.Loaded -= this.AssociatedObjectLoaded; base.OnDetaching(); } private void AssociatedObjectLoaded(object sender, RoutedEventArgs e) { if (this.DataType == null || !typeof(IPageViewModel).IsAssignableFrom(this.DataType)) { throw new InvalidOperationException("PageViewModelBehavior.DataType is not set. Page: " + this.AssociatedObject.GetType().Name); } this.AssociatedObject.DataContext = Activator.CreateInstance(this.DataType); // TODO: Call load on your page view model etc. } private void AssociatedObjectUnloaded(object sender, RoutedEventArgs e) { // TODO: Call unload on your page view model etc. // Allow the throw-away view model to be GC'd this.AssociatedObject.DataContext = null; } } </code></pre> <p>This ensures the page is bound again each time the user navigates back to the page. This also allows you to use your favourite IOC container to create the ViewModel.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload