WPF:在分离时禁用绑定更新 [英] WPF: disable bindings update on detach

查看:185
本文介绍了WPF:在分离时禁用绑定更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是这样的情况:我有一个编辑器应用程序,编辑一些分层数据。数据本身保存在ViewModel类中,View类负责反映ViewModel中的更改。 View的主要部分是ContentControl。当ViewModel中的数据发生变化时,会重新生成控件的层次结构,顶级控件将成为ContentControl的内容。当然,这些分级控件有绑定。
现在是关闭编辑器的时候了。 ViewModel对命令做出反应并清除数据。 PropertyChanged被提出,并且View已准备好作出反应:它尝试执行

Here is the situation: I have an editor app, that edits some hierarchical data. The data itself is held in ViewModel class, and View class is responsible to reflect changes in ViewModel. The main part of the View is ContentControl. When data changes in ViewModel, a hierarchical structure of controls is (re)generated and top-level control becomes the Content of the ContentControl. Of course, those hierarchical controls have bindings. Now it's time to close the editor. ViewModel reacts to command and clears the data. PropertyChanged is raised and the View is ready to react: it attempts to do

myContentControl.Content = null;

但这是陷阱的地方:WPF从ContentControl的视觉树和重新评估绑定。但是数据已经被破坏了!

But this is where the pitfall is: WPF detaches hieararchy of controls from ContentControl's visual tree and re-evaluates bindings. But the data is already destroyed!

我该怎么办?为什么WPF更新绑定视觉树的 的控件上的绑定?当然,我可以额外检查null,但是是否有一种在半死控制上完全没有约束力的方法?

What should I do? Why WPF updates bindings on controls that go out of visual tree? Of course I can do additional check for nulls, but is there a way not to do binding at all on half-dead controls?

推荐答案

p>每当我们有一个使用户能够编辑对象的UI,同时也提供了保存或取消的可能性,我们只需要为该视图使用另一个视图模型类。

Whenever we have a UI that enables a user to edit an object, but also provides the possibility of saving or cancelling, we simply need to use another view model class for that view.

因此,编辑开始时,将视图模型中的字段从当前对象复制到可编辑属性。然后我们让用户编辑他们想要的内容。如果它们取消操作,那么我们什么都不做,因为原始对象是不变的。

Therefore, when editing starts you copy the fields from the current object to the editable properties in the view model. We then leave the user to edit what they want. If they cancel the operation, then we do nothing, as the original object is untouched.

但是,如果要保存,那么我们从编辑的视图中复制属性模型到原始对象并保存。然后,视图和视图模型可以无后顾之忧。

However, if they want to save, then we copy the properties from the edited view model to the original object and save it. Then the view and view model can be disposed of without consequence.

这篇关于WPF:在分离时禁用绑定更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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