LostFocus pinning does not work when using access keys
Please consider the following example. Note that in real word, the binding source is likely to be a data object. I am using TextBlock
for simplicity.
<Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel Margin="20">
<Label>Enter a Name:</Label>
<TextBox x:Name="txt_Name" Text="{Binding ElementName=display_name, Path=Text, UpdateSourceTrigger=LostFocus}" />
<Label>The name you entered:</Label>
<TextBlock x:Name="display_name" />
<Button x:Name="btn_Save" Click="SaveClick">_Save</Button>
</StackPanel>
</Window>
Class Window1 Private Sub SaveClick(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) MessageBox.Show("Saving your name as: " & display_name.Text) End Sub End Class
In the above example, if I enter a name "Joe"
in TextBox
and click the Save button, it is TextBlock
updated after LostFocus
and the data is "saved" as expected. Things are good.
However, if I then type "Bob"
in TextBox
and use the passkey (Alt-S) to save, TextBlock
it is not updated because the event LostFocus
is TextBox
not fired. As a result, my binding source is not updated and the wrong value is stored (i.e. "Joe"
).
In most WPF input fields, TextBox
you'll want to check for LostFocus
(not PropertyChanged
); however, if the event LostFocus
does not fire (and hence the binding is not updated) when the access token is used, how do we check the entry? In WinForms, we have Validating
and events Validated
, but they are absent in WPF.
source to share
Okay, if you're more interested in a real world scenario than your contrived example, you can set a binding on the textbox to update the data rather than lose focus and the data will be saved in both scenarios without any ugly hacks. The only issue (which is mentioned in the WPF documentation for Bindings) is that it can affect the performance of your application. If you are working on some even relatively new machine, you will not notice the difference (I don't know).
source to share