我有一个wpf窗口,允许用户编辑财务帐户;该窗口是从我的数据库中填充的。
这是我的FinancialAccount类的相关部分:
Public Class FinancialAccount
AccountName as String
Notes as String
....
End Class
在窗口上,用户可以从ComboBox中单击要编辑的帐户,然后在该窗口的其余部分填充该帐户的数据,并将DataContext设置为fa,即FinancialAccount的选定实例类。参见下图。
我们将重点放在“注释”字段上。它在XAML中的绑定如下:
<TextBox
x:Name="txtNotes"
Text="{Binding Path=Notes}">
</TextBox>
以及“退出”按钮和Notes文本框的事件处理程序为:
Private Sub btnExit_Click(sender As Object, e As RoutedEventArgs) Handles btnExit.Click
Debug.WriteLine($"Exit: {fa.Notes}")
SaveAccount()
Close()
End Sub
和
Private Sub txtNotes_LostKeyboardFocus(sender As Object, e As KeyboardFocusChangedEventArgs) Handles txtNotes.LostKeyboardFocus
Debug.WriteLine($"LostKeyboardFocus: {fa.Notes}")
End Sub
这两个Debug语句很重要。现在假设我将“ efgh”附加到Notes文本框中的文本,然后单击“退出”按钮;这是Debug语句的结果:
LostKeyboardFocus: abcd
Exit: abcd
LostKeyboardFocus: abcdefgh
这里重要的是,单击“退出”按钮后,将不会运行SaveAccount例程,这样就不会将新数据发送回数据库。
问题
● Why does the TextBox LostKeyboardFocus event fire twice?
● Why is the entered text not bound to the DataContext until the second time the event fires?
● How can I implement this so that the entered text is actually saved?