textbox回車事件中拿不到text的處理辦法(wpf)


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM