DataTemplate x:Shared=false has no impact on the view
Asked Answered
N

1

8

I am using datatemplate to load my views using PRISM 4 discovery. I have a need to create the view/viewmodel multiple times rather than reuse existing instances so I set x:Shared=false in the resource but it only has impact on the viewmodel. I can confirm that the viewmodel is not reused but the view is. The view constructor is only called once the first time it is called. I have read similar posts here but their solutions did not work for me. I want to know if I can some how extend the resource loader/locator and make sure it respects the Shared flag.

Here is how my template is defined:

 <DataTemplate DataType="{x:Type CVM:MyViewModel}" x:Shared="False">
        <V:MyView />
 </DataTemplate>
Northwester answered 31/5, 2012 at 18:59 Comment(4)
Any workaround without having to change the design?Northwester
Don't know, haven't used prism and can't really think of anything elegant.Hemichordate
In Prism you control if you want singleton or not through the PartCreationPolicy attribute. Shared = singleton, NonShared = a new instance. Have you decorated your view with [PartCreationPolicy(CreationPolicy.NonShared)]?Vespertilionine
Thanks Meeleak, I just tested it. It works for the viewmodel but not for the view. The view constructor is still only called once.Northwester
P
0

All the DataTemplate contains is a 'Template' for creating the necessary Visual Tree for when the object (in your case the viewmodel) comes into view.

Therefore if only one of you 'MyViewModel' objects is in view then the contructor for you view will only be called once (even if multiple Viewmodels are instantiated). If you had several of your viewmodels in view, then the constructor for your view will be called multiple times as the Template of your DataTemplate gets properly constructed and added to the Visual Tree (once for each ViewModel).

However, if your ItemsControl (that holds your viewmodels) has virtualisation switched on, then only one 'container' (which in simplified terms will be your datatemplate) may exist, and may be re-used.

Parlour answered 1/6, 2012 at 12:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.