WPF智能輸入提示是用一個textBox和Popup完成的,下面看具體代碼:
<Window x:Class="WPFPopup.ABCD"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ABCD" Height="300" Width="300">
<Grid>
<TextBox Canvas.Left="371" Canvas.Top="25" Height="23" Name="textBox1" Width="120" KeyUp="textBox1_KeyUp" Margin="75,79,83,159" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="75,44,0,0" Name="textBlock1" Text="TextBlock" VerticalAlignment="Top" Width="155" />
</Grid>
</Window>
namespace WPFPopup
{
/// <summary>
/// ABCD.xaml 的交互邏輯
/// </summary>
public partial class ABCD : Window
{
public List<string> listStr;
public ABCD()
{
InitializeComponent();
listStr = new List<string>();
listStr.Add("a");
listStr.Add("ab");
listStr.Add("abc");
listStr.Add("abcd");
listStr.Add("b");
listStr.Add("bc");
listStr.Add("bcd");
listStr.Add("c");
listStr.Add("cd");
listStr.Add("d");
listStr.Add("da");
listStr.Add("dab");
listStr.Add("dabc");
}
public Popup pop = new Popup();
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (textBox1.Text != "")
{
var item = listStr.Where(a => a.Contains(textBox1.Text));
if (item.ToList<string>().Count > 0)
{
pop = this.createPopup(pop, item.ToList<string>(), textBox1);
pop.IsOpen = true;
}
else
{
pop.IsOpen = false;
}
}
else
{
pop.IsOpen = false;
}
}
public void listbox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
ListBox box = sender as ListBox;
string itemvalue = box.SelectedValue as string;
this.textBlock1.Text = itemvalue;
this.textBox1.Text = itemvalue;
pop.IsOpen = false;
}
public Popup createPopup(Popup pop, List<string> listSource, UIElement element)
{
Border border = new Border();
border.BorderBrush = new SolidColorBrush(Colors.Black);
//border.BorderThickness = new Thickness(1.0);//設置邊框寬度
StackPanel panel1 = new StackPanel();
panel1.Children.Clear();
panel1.Background = new SolidColorBrush(Colors.LightGray);
ListBox listbox = new ListBox();
listbox.Background = new SolidColorBrush(Colors.WhiteSmoke);
listbox.MinWidth = 100;
listbox.Height = 120;
listbox.ItemsSource = listSource;
listbox.MouseDoubleClick += new MouseButtonEventHandler(listbox_MouseDoubleClick);
panel1.Children.Add(listbox);
border.Child = panel1;
pop.Child = border;
pop.PlacementTarget = element;
return pop;
}
}
}