在程序退出之前更新依赖属性
我在 RichTextBox 上创建了一个 Binary 类型的依赖属性,它允许我绑定到 ViewModel 中二进制形式 (byte[]) 的 FlowDocument。这效果很好,属性可以正确转换和返回。
每当 RichTextBox 失去焦点时,依赖属性的值就会使用 FlowDocument 的新二进制表示形式进行更新。
我的问题是,如果我一直在使用 RichTextBox 并关闭窗口,则 RichTextBox 不会失去焦点,因此依赖项属性不会使用 FlowDocument 的新二进制表示形式进行更新,因此新更改不会提交到数据库。在我的 ViewModel 中,我有一个 CleanUp 方法,当 ViewModel 准备好处置时会调用该方法,我可以在其中保存更新的文档。
如果用户单击关闭窗口,RichTextBox 不会失去焦点,如何让依赖属性自行更新? 我集思广益如下:
- 告诉依赖属性通过消息广播更新自身。我不清楚如何在依赖属性中注册消息侦听器。
- 直接查询RichTextBox,获取Document,手动将其转换为二进制对象。
- 获取视图以将焦点移至虚拟控件,以便依赖属性现在自行更新。
你们觉得怎么样?
更新:依赖属性的 onchanged 事件添加了一个等待 RichTextBox 失去焦点的事件处理程序。正是这个处理程序用它的新值更新依赖关系。
I have created a dependency property of type Binary on a RichTextBox which allows me to bind to a FlowDocument which is in binary form (byte[]) within the ViewModel. This works well, the property converts to and back correctly.
Whenever the RichTextBox looses focus then the value of the dependency property is updated with the new binary representation of the FlowDocument.
My problem is that if I have been using the RichTextBox and I close the window, the RichTextBox does not lose focus and hence the dependency property is not updated with the new binary representation of the FlowDocument and therefore new changes are not commited to the database. In my ViewModel I have a method CleanUp which gets called when a ViewModel is getting ready to be disposed, where I can save the updated document.
How can I get the dependency property to update itself as the RichTextBox doesn't lose focus if the user clicks to close the window?
I brainstormed the following:
- Tell the dependency property to update itself via a message broadcast. I am not clear on how to register a message listener within the dependency property.
- Query the RichTextBox directly, get the Document, convert it to a binary object manually.
- Get the view to move focus to a dummy control, so that the dependency property now updates itself.
What do you guys think?
Update: the on changed event for the dependency property adds a event handler which is waiting for the RichTextBox to loose focus. It is this handler that updates the dependency with its new value.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是什么阻止您处理窗口的关闭/关闭事件以及移动焦点或更新绑定?
What's stopping you from handling the closing/closed event of the Window and moving focus or updating the binding?
使用“PropertyChanged”的 UpdateSourceTrigger
类似:
Use an UpdateSourceTrigger of "PropertyChanged"
Something like:
我曾经遇到过类似的问题,我使用的解决方案是将焦点移至不同的控件,但我从未遇到过任何问题。
就我而言,窗口中有几个可编辑控件,因此我不必使用虚拟控件。
I had a similar problem once, the solution I used was to move the focus to a different control and I never had any problems with this.
In my case there were several editable controls in the window so I didn't have to use a dummy control.