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 "deta开发者_JAVA技巧ils" 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!
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}" />
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();
精彩评论