DataTemplate x:Shared=false has no impact on the v

2019-02-14 04:37发布

问题:

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>

回答1:

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.



标签: wpf prism-4