带有文本框的 WPF 弹出窗口?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24327212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 11:57:41  来源:igfitidea点击:

WPF popup with textbox?

c#wpf

提问by theOne

I am trying to create a control that displays search results as a user types something in a textbox. For this, I have a textbox and a popup that shows up when the user types something into it (just like a google search box). Like so,

我正在尝试创建一个控件,该控件在用户在文本框中键入内容时显示搜索结果。为此,我有一个文本框和一个弹出窗口,当用户在其中输入内容时会显示该弹出窗口(就像 Google 搜索框一样)。像这样,

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

Now when the user starts typing into the textbox i want the popup to show and stay open until the user focusses on some other ui control or if the text entered is empty. I am unable to achieve this easily and was wondering if there are alternate better ways of doing this in wpf. Regards

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

回答by eran otzap

XAML :

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 :

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;
    }
}