textbox回车事件中拿不到text的处理办法(wpf)
生活随笔
收集整理的這篇文章主要介紹了
textbox回车事件中拿不到text的处理办法(wpf)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
wpf做一個(gè)搜索框,想要在回車時(shí)搜索框內(nèi)的文字。
?
<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時(shí),雖然都綁定了相同的SearchCommand,但是結(jié)果不同。回車進(jìn)入斷點(diǎn)看Keyword的內(nèi)容和按button看到的內(nèi)容不同,可能是在viewmodel中綁定的屬性值沒能及時(shí)的更新為搜索框中的文字。那么在什么情況下能更新呢,經(jīng)過測試,在焦點(diǎn)從文本框離開時(shí)會觸發(fā)更新,于是增加PreviewKeyDown來引發(fā)焦點(diǎn)離開。
private void SearchBox_OnKeyDown(object sender, KeyEventArgs e){if (e.Key == Key.Enter){SearchBox.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));}}?
?
?
?
------------------
還有一個(gè)簡單的處理方法,設(shè)置Button的IsDefault="True",不過這種方法將導(dǎo)致所有的textbox回車都引發(fā)buttonclick
轉(zhuǎn)載于:https://www.cnblogs.com/devourer/p/3382576.html
總結(jié)
以上是生活随笔為你收集整理的textbox回车事件中拿不到text的处理办法(wpf)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Union与Union All的区别
- 下一篇: 初探弹出层的实现原理