WPF弹出文本框

本文关键字:文本 WPF | 更新日期: 2023-09-27 18:09:36

我正在尝试创建一个控件,显示搜索结果作为用户在文本框中键入的东西。为此,我有一个文本框和一个弹出框,当用户在其中输入内容时显示(就像谷歌搜索框)。一样,

<Grid> <TextBox Name="userEntry" /> <Popup /> </Grid>

现在当用户开始输入文本框时,我希望弹出框显示并保持打开状态,直到用户关注其他ui控件或输入的文本为空。我无法轻松实现这一点,想知道是否有更好的替代方法在wpf中做到这一点。关于

WPF弹出文本框

XAML:

  <Window>
     <Grid>
        <Grid.RowDefinitions>
             <RowDefinition />
             <RowDefinition />
        </Grid.RowDefinitions>
        <Button x:Name="btn" Content="Open Search Window"  Height="30" Width="150" Click="btn_Click"/> 
        <Popup x:Name="popup"  PlacementTarget="{Binding ElementName=btn}" Placement="Bottom"  Width="200" Height="100" Margin="0,20,0,0">
           <Border BorderBrush="Black" BorderThickness="2" Background="AliceBlue">
               <TextBox x:Name="txtBox" VerticalAlignment="Center" Margin="15,0,15,0"/> 
           </Border>
        </Popup>
        <TextBox x:Name="focusTarger" Text="Focus Me !" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" TextAlignment="Center" FontSize="16"/>
    </Grid> 
  </Window>

CS:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        GotFocus += MainWindow_GotFocus;
    }
    void MainWindow_GotFocus(object sender, RoutedEventArgs e)
    {
        FrameworkElement element = (FrameworkElement)e.OriginalSource;
        if (txtBox == element || popup == element || element.Parent == popup)
            return;
        popup.IsOpen = !string.IsNullOrEmpty(txtBox.Text);
    }
    private void btn_Click(object sender, RoutedEventArgs e)
    {
        popup.IsOpen = true;
    }
}