views:

2047

answers:

3

I have a WPF window for editing database information, which is represented using an entity framwork object. When the user closes the window, I'd like to notice in the Closing event whether the information has changed and show a message box offering to save the changes to the database.

Unfortunately, changes to the currently focused edit aren't assigned to the binding source until the edit loses focus, which happens at some point after the Closing event has been processed.

Ideally, there would be a routine which commits all changes in the view hierarchy that I could call before checking to see if my entity has been modified. I've also looked for information on programmatically clearing the focus in the control with focus, but can't figure out how to do it.

My question is, how is this typically handled? Thanks for any comments.

+2  A: 
Donnelle
A: 

Also look at the sugestions in this post

rudigrobler
A: 

The easiest way is to set the focus somewhere. You can set the focus back immediately, but setting the focus anywhere will trigger the LostFocus-Event on any type of control and make it update its stuff:

IInputElement x = System.Windows.Input.Keyboard.FocusedElement;
DummyField.Focus();
x.Focus();

Another way would be to get the focused element, get the binding element from the focused element, and trigger the update manually. An example for TextBox and ComboBox (you would need to add any control type you need to support):

TextBox t = Keyboard.FocusedElement as TextBox;
if ((t != null) && (t.GetBindingExpression(TextBox.TextProperty) != null))
  t.GetBindingExpression(TextBox.TextProperty).UpdateSource();
ComboBox c = Keyboard.FocusedElement as ComboBox;
if ((c != null) && (c.GetBindingExpression(ComboBox.TextProperty) != null))
  c.GetBindingExpression(ComboBox.TextProperty).UpdateSource();
Sam