如何设置焦点/位置插入符号到SearchBox

时间:2016-02-13 10:43:01

标签: c# .net win-universal-app

我有这个布局:

    <RelativePanel>
        <ButtonContent="&#xE700;" Name="btHumburger"/>
        <Button Content="&#xE0A6;" Name="btBack"/>
        <TextBlock Text="Home" Name="tbHeader"/>
        <Button Content="&#xE11A;" Name="btSearch"/>
        <SearchBox Visibility="Collapsed" Name="asbSearch" LostFocus="asbSearch_LostFocus"/>
    </RelativePanel>

我只想在按下按钮SearchBox时显示btSearch,并在焦点丢失时隐藏它。在codebehind中:

    private void btSearch_Click(object sender, RoutedEventArgs e)
    {
        asbSearch.Visibility = Visibility.Visible;
        asbSearch.Focus(FocusState.Programmatic);

        btHumburger.Visibility = Visibility.Collapsed;
        btBack.Visibility = Visibility.Collapsed;
        tbHeader.Visibility = Visibility.Collapsed;
        btSearch.Visibility = Visibility.Collapsed;
    }

    private void asbSearch_LostFocus(object sender, RoutedEventArgs e)
    {
        asbSearch.Visibility = Visibility.Collapsed;

        btHumburger.Visibility = Visibility.Visible;
        btBack.Visibility = mainFrame.CanGoBack ? Visibility.Visible : Visibility.Collapsed;
        tbHeader.Visibility = Visibility.Visible;
        btSearch.Visibility = Visibility.Visible;
    }

但是asbSearch asbSearch.Focus(FocusState.Programmatic);之后LostFocus没有专注/放置插入符号,因此{{1}}事件不会触发。如何处理?

1 个答案:

答案 0 :(得分:1)

在设置焦点之前尝试调用asbSearch.UpdateLayout();

似乎Visibility更改未完全完成,控件在此之前无法获得焦点。