DataTemplate x:Shared = false对视图没有影响 [英] DataTemplate x:Shared=false has no impact on the view

查看:174
本文介绍了DataTemplate x:Shared = false对视图没有影响的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用datatemplate通过PRISM 4发现加载视图.我需要多次创建视图/视图模型,而不是重复使用现有实例,因此我在资源中设置了x:Shared = false,但这仅对视图模型产生影响.我可以确认视图模型没有被重用,但是视图却被重用了.视图构造函数仅在第一次调用时被调用一次.我在这里阅读过类似的帖子,但是他们的解决方案对我不起作用.我想知道是否可以扩展资源加载器/定位器并确保它尊重Shared标志.

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>

推荐答案

所有DataTemplate包含的是'Template',用于在对象(在您的情况下为viewmodel)进入视图时创建必要的可视树.

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.

因此,如果只有一个'MyViewModel'对象在视图中,则视图的构造器将仅被调用一次(即使实例化了多个Viewmodel).如果在视图中有多个视图模型,则当正确构建DataTemplate的模板并将其添加到可视树(每个ViewModel一次)时,将多次调用该视图的构造函数.

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).

但是,如果您的ItemsControl(用于保存您的视图模型)已开启虚拟化功能,则可能仅存在一个容器"(简而言之就是您的数据模板),并且可以重复使用.

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.

这篇关于DataTemplate x:Shared = false对视图没有影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆