wpf做一个搜索框,想要在回车时搜索框内的文字。
<TextBox x:Name="SearchBox" Grid.Column="1" Margin="350,35,52,21" Width="122" Height="34" RenderTransformOrigin="0.5,0.5" Text="{Binding Keyword}" PreviewKeyDown="SearchBox_OnKeyDown"><TextBox.InputBindings><KeyBinding Key="Enter" Command="{Binding SearchCommand}" /></TextBox.InputBindings></TextBox><Button x:Name="btnSearch" Grid.Column="2" HorizontalAlignment="Left" Height="34" Margin="29.5,38,0,0" VerticalAlignment="Top" Width="34" Command="{Binding SearchCommand}" ><Image Height="34" Width="34" Source="/Icons/SearchIcon.png"/></Button>
在不加PreviewKeyDown时,虽然都绑定了相同的SearchCommand,但是结果不同。回车进入断点看Keyword的内容和按button看到的内容不同,可能是在viewmodel中绑定的属性值没能及时的更新为搜索框中的文字。那么在什么情况下能更新呢,经过测试,在焦点从文本框离开时会触发更新,于是增加PreviewKeyDown来引发焦点离开。
private void SearchBox_OnKeyDown(object sender, KeyEventArgs e){if (e.Key == Key.Enter){SearchBox.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));}}
------------------
还有一个简单的处理方法,设置Button的IsDefault="True",不过这种方法将导致所有的textbox回车都引发buttonclick