Hello,
Welcome to Microsoft Q&A!
For example, if the user type "abc", this value will send to the source object if the user hit "Enter" or "Ctrl+M", otherwise this new value will be discarded if lost focus.
You need to change the UpdateSourceTrigger
Property to Explicit. This will make sure the UI change will not be saved to the source immediately. Then you could call BindingExpression.UpdateSource
when user press the Enter key to update the source you need.
I've made a simple demo to show how it works. You could try to check this.
Xaml parts:
<StackPanel x:Name="RootPanel" Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBox x:Name="MyTextBox" Width="200" Height="80" Text="{Binding TextStr,UpdateSourceTrigger=Explicit,Mode=TwoWay}" KeyDown="MyTextBox_KeyDown"/>
<Button Content="Click" Click="Button_Click"/>
</StackPanel>
Code-behind
public sealed partial class MainWindow : Window, INotifyPropertyChanged
{
private string _TextStr;
public string TextStr
{
get
{
return _TextStr;
}
set
{
_TextStr = value;
RaisePropertychangedEvent("TextStr");
}
}
public MainWindow()
{
this.InitializeComponent();
TextStr = "ABC";
RootPanel.DataContext = this;
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertychangedEvent(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Debug.WriteLine(TextStr);
}
private void MyTextBox_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Enter)
{
BindingExpression be = MyTextBox.GetBindingExpression(TextBox.TextProperty);
be.UpdateSource();
}
}
}
When I type something in the TextBox
and click the button, the TextStr output is still the original. If I press enter key when the TextBox
is focused, the binding will be updated, and the TextStr output will become the new value.
Thank you.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.