Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force WPF to Commit Changes on Focused Element

I'm working with VS2010, WPF and EF. I've placed controls on my window by dragging an entity out of the Data Sources toolwindow. I used the "details" setting so my entity is represented by several labels and textboxes. I've also added a button with the following code:

_context.SaveChanges();

When I'm editing data, the changes in whichever textbox has focus are not committed back to the DB. Everything else commits just fine. If I shift focus to another element prior to hitting the save button, it commits as well. I've experienced the same thing with the DataGrid.

I know I'm missing something simple, but I can figure it out. Any ideas on what I'm missing?

Thanks!

like image 976
John Laffoon Avatar asked Apr 15 '10 13:04

John Laffoon


2 Answers

This is because TextBox's default Binding UpdateSourceTrigger is LostFocus. If you modify all your Bindings to set this to PropertyChanged, it will work like you expect:

<TextBox Text="{Binding SomeProperty, UpdateSourceTrigger=PropertyChanged}" />
like image 165
Abe Heidebrecht Avatar answered Nov 07 '22 05:11

Abe Heidebrecht


I just ran into this same issue when trying to set the value of a databound TextBox programmatically, but Abe's suggestion didn't work for our setup (it was causing some erratic validation behavior).

Here's how I got it to work:

TextBox tb = (TextBox)this.FindName("TargetTextBox");
tb.Text = "1234";
tb.GetBindingExpression(TextBox.TextProperty).UpdateSource();
like image 27
Stephen Gierek Avatar answered Nov 07 '22 05:11

Stephen Gierek