开发者

Update Dependency Property prior to program exit

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:

  1. 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.
  2. Query the RichTextBox directly, get the Document, convert it to a binary object manually.
  3. 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 Rich开发者_开发问答TextBox to loose focus. It is this handler that updates the dependency with its new value.


Use an UpdateSourceTrigger of "PropertyChanged"

Something like:

{Binding Path=MyProperty, 
                    Mode=TwoWay,
                    UpdateSourceTrigger=PropertyChanged}


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.


What's stopping you from handling the closing/closed event of the Window and moving focus or updating the binding?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜