Reputation: 11369
Given a std record edit form using WPF two way binding to a EF entity object
The IsDirty is handled as follows
entity.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(ct_PropertyChanged);
DataContext = entity;
void entity_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
IsDirty = true;
}
void SaveAndClose()
{
if ( IsDirty ) { // doSave }
Close();
}
Everything works great except if the user changes just fieldX and hits save ( which is a valid model in this case !)
The problem is PropertyChanged() is NOT called till Close() executes so the record is NOT saved
Any way to force the "Binder" or any other alternatives ?
Upvotes: 3
Views: 836
Reputation: 8039
The default Binding UpdateSourceTrigger is LostFocus which means that your binding will update the underlaying value when your control will loses Focus. You can change that to PropertyChanged so it will update the source as soon as the user clicks it (or types in if it's a TextBox).
Upvotes: 1
Reputation: 375
I suppose the UpdateSourceTrigger
is LostFocus
so the Property is updated when the control (filedX) loses the focus. E.g. the user clicks sets the cursor into an other control.
One possibility is, to set the UpdateSourceTrigger
to PropertyChanged
.
Another way is to force the currently focused element to update the source.
Here is an example for a TextBox:
var focusedElement = Keyboard.FocusedElement;
if(focusedElement is TextBox)
{
var bindingExpression = ((TextBox)focusedElement).GetBindingExpression(TextBox.TextProperty);
if(bindingExpression != null)
{
bindingExpression.UpdateSource();
}
}
Upvotes: 1