如何跟踪 DataTemplate 的所有实例或 DataTemplate 中的控件?
我正在使用 DataTemplate 将视图应用到 ViewModel。我有一种情况,当视图(DataTemplate)的一个实例中发生某一件事时,我需要在所有其他实例中采取一项操作。
我已经通过在 DataTemplate 中的一个控件上实现 Initialized 事件并使用该事件将对控件的引用添加到代码隐藏中的列表来实现此目的。这是有效的,因为 DataTemplate 只有一个代码隐藏(在资源字典中),它们都可以访问同一个列表。
不过,我有点担心,因为 DataTemplate 的实例被创建和销毁。我是否没有保留对不再需要的 DataTemplate 旧实例的额外引用?有什么办法可以清理它们吗?当控件或数据模板消失时,是否有相应的事件...与初始化相反...?
I'm using a DataTemplate to apply a View to a ViewModel. I have a case where when a certain thing happens in one instance of the View (DataTemplate), I need to take an action in all other instances.
I'm already accomplishing this by implementing the Initialized event on one of the controls in the DataTemplate, and using that event to add a reference to the control to a list in the codebehind. This is working, since there's only one codebehind for the DataTemplate (in a resource dictionary), they can all access the same list.
I'm a bit worried though, since instances of the DataTemplate get created and destroyed. Am I not keeping extra references around to old instances of the DataTemplate that are no longer necessary? Is there some way I can clean them up? Is there a corresponding event... the opposite of Initialized... when a control or DataTemplate is gone?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
直接在 ViewModel 中建模这种交互对您来说是否可行?也许与数据绑定的项目上的属性或事件有关?这样,您的视图只需决定事件的行为/呈现。
Would it be feasible for you to model this interaction directly in the ViewModel? Perhaps with a property or event on the item(s) being data-bound? That way your view only has to decide the behavior/presentation of the event.