[英]WPF TextBox lostFocus event trigger
I am new to WPF, In my mainWindow I have multiple TextBox, so whenever a user enters different inputs in these textbox I want to implement those changes in the code behind, as soon as user leaves the focus of the textbox. 我是WPF的新手,在mainWindow中,我有多个TextBox,因此每当用户在这些文本框中输入不同的输入时,只要用户离开文本框的焦点,我都希望在代码中实现这些更改。
For example, my textBox looks like this: 例如,我的textBox看起来像这样:
<TextBox Name="SpiralAngleTextBox"
Grid.Column="1" Grid.Row="4"
Margin="5,5,5,5" SelectedText="0"/>
I am not looking to do any kind of input validation. 我不打算进行任何形式的输入验证。 What I want is to trigger some calculations or call a function whenever the TextBox leaves focus after contents of TextBox is updated.
我想要的是在TextBox的内容更新后,只要TextBox离开焦点,就触发一些计算或调用一个函数。
You can write an EventHandler 您可以编写一个EventHandler
<TextBox Name="SpiralAngleTextBox"
Grid.Column="1" Grid.Row="4"
Margin="5,5,5,5" SelectedText="0" LostFocus="SpiralAngleTextBox_LostFocus"/>
and in the xaml.cs 并在xaml.cs中
private void SpiralAngleTextBox_LostFocus(object sender, RoutedEventArgs e)
{
foo();
}
If you just want it to do stuff when the textbox content changes you can try something like this: 如果您只希望它在文本框内容更改时做一些事情,可以尝试执行以下操作:
<TextBox Name="SpiralAngleTextBox"
Grid.Column="1" Grid.Row="4"
Margin="5,5,5,5" SelectedText="0" LostFocus="SpiralAngleTextBox_LostFocus"
TextChanged="SpiralAngleTextBox_TextChanged"/>
and in the xaml.cs 并在xaml.cs中
bool hasChanged;
private void SpiralAngleTextBox_LostFocus(object sender, RoutedEventArgs e)
{
if(hasChanged)
foo();
hasChanged = false;
}
private void SpiralAngleTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
hasChanged = true;
}
All you need to do is to bind to TextBox.Text 您需要做的就是绑定到TextBox.Text
<TextBox Text="{Binding MyProperty}" />
Where MyProperty is some property in your code-behind. MyProperty是代码隐藏中的某些属性。 This is because TextBox.Text updates on lost focus (UpdateSourceTrigger=LostFocus by default.) You can learn more here: https://docs.microsoft.com/en-us/dotnet/framework/wpf/data/how-to-control-when-the-textbox-text-updates-the-source
这是因为TextBox.Text在失去焦点时进行更新(默认情况下为UpdateSourceTrigger = LostFocus。)您可以在此处了解更多信息: https : //docs.microsoft.com/zh-cn/dotnet/framework/wpf/data/how-to-控制时最文本框,文本更新-在源
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.