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.

0


source to share


3 answers


You can do it manually before saving using:

txt_Name.GetBindingExpression(TextBox.TextProperty).UpdateTarget();

      



A bit ugly, but it works.

+2


source


You can also change focus in a click handler before reading the value, for example, forcing focus on a button or other text field



This is another "ugly but it works" solution, and might be appropriate if you have many controls or don't want to mess with their binding expressions.

+1


source


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).

+1


source







All Articles