我正在尝试创建一个控件,当用户在文本框中键入内容时显示搜索结果。为此,我有一个文本框和一个弹出窗口,当用户输入内容时会显示(就像谷歌搜索框一样)。像这样,
<Grid> <TextBox Name="userEntry" /> <Popup /> </Grid>
现在,当用户开始在文本框中键入内容时,我希望弹出窗口显示并保持打开状态,直到用户专注于其他一些ui控件或输入的文本为空。 我无法轻易实现这一点,并且想知道是否有更好的方法在wpf中执行此操作。 此致
答案 0 :(得分:0)
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;
}
}