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

扶醉桌前 提交于 2019-11-30 05:43:30

问题


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.



来源:https://stackoverflow.com/questions/10839633/datatemplate-xshared-false-has-no-impact-on-the-view

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!