WPF TextBox update binding when focus lost, or Enter key pressed, or click outside

I have a WPF TextBox, bound to a backing data variable, two way, set to update on FocusLost. It looks something like this:
<TextBox Name="xyzzy" Binding="{Binding MyData, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" />

Open in new window


Issues:
1. I find myself pressing the Enter key when I'm finished editing the TextBox. I'd like the binding to update itself when I press the Enter key.

2. I'd also like the binding to update itself when I click outside of the TextBox, even if I click on something that isn't focusable. Currently clicking on something outside the TextBox that isn't focusable does not make the TextBox lose focus, so the binding isn't updated.
deleydAsked:
Who is Participating?
 
louisfrCommented:
1. Handle the TextBox's KeyDown event
2. Handle the Window's MouseDown event
Here's a sample window with associated code I made:
<Window x:Class="TopCoder.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TopCoder"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525" MouseDown="Window_MouseDown">
    <StackPanel>
        <TextBox Name="xyzzy" Text="{Binding MyData, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" Margin="0 50" KeyDown="xyzzy_KeyDown"/>
    </StackPanel>
</Window>

Open in new window

public partial class MainWindow : Window
{
    BindingExpression b;
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new Data();
        b = BindingOperations.GetBindingExpression(xyzzy, TextBox.TextProperty);
    }

    private void xyzzy_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter && b.IsDirty)
            b.UpdateSource();
    }

    private void Window_MouseDown(object sender, MouseButtonEventArgs e)
    {

        if (b.IsDirty)
            b.UpdateSource();
    }
}

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.