Check WPF on Enter Key Up

I am trying to check for a change in the user interface when I press Enter. The user interface element is a text field that binds data to a string. My problem is that the data binding did not update TestText when the Enter key is Up. It is updated only after clicking the button that brings up the message box.

/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window, INotifyPropertyChanged
{
    String _testText = new StringBuilder("One").ToString();
    public string TestText
    {
        get { return _testText; }
        set { if (value != _testText) { _testText = value; OnPropertyChanged("TestText"); } }
    }


    public Window1()
    {
        InitializeComponent();
        myGrid.DataContext = this;
    }

    private void OnPropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void onKeyUp(object sender, KeyEventArgs e)
    {
       if (e.Key != System.Windows.Input.Key.Enter) return;
       System.Diagnostics.Trace.WriteLine(TestText);
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show(TestText);
    }

}

XAML window:

Window x:Class="VerificationTest.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" KeyUp="onKeyUp"

TextBox XAML:

TextBox Name="myTextBox" Text="{Binding TestText}"

XAML Button:

Button Name="button1" Click="button1_Click"
+5
source share
1 answer

To force a TextBox to pass the value back to the binding source, you can:

var binding = myTextBox.GetBindingExpression(TextBox.TextProperty);
binding.UpdateSource();

, Text, , .

<TextBox Name="myTextBox"
         Text="{Binding TestText, UpdateSourceTrigger=PropertyChanged}" />

. , , - , TextBox, OnKeyDown, , UpdateSource, , SelectAll TextBox, , "" . TextBox , , , .

+10

All Articles