1、添加一个数据实体类 AutoCompleteEntry,如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace FCClient.AppCode
{
public class AutoCompleteEntry
{
private string[] keywordStrings;
private string displayString; public string[] KeywordStrings
{
get
{
if (keywordStrings == null)
{
keywordStrings = new string[] { displayString };
}
return keywordStrings;
}
} public string DisplayName
{
get { return displayString; }
set { displayString = value; }
} public AutoCompleteEntry(string name, params string[] keywords)
{
displayString = name;
keywordStrings = keywords;
} public override string ToString()
{
return displayString;
}
}
}

2、创建一个继承至Canvas的控件,并命名为AutoCompleteTextBox,前台 AutoCompleteTextBox.xam l代码,如下:

<Canvas x:Class="FCClient.CustomControls.AutoCompleteTextBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="30" Width="300">
</Canvas>

3、后台 AutoCompleteTextBox 代码,如下:

using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Timers; using FCClient.AppCode; namespace FCClient.CustomControls
{
/// <summary>
/// 自定义自动匹配文本框
/// </summary>
public partial class AutoCompleteTextBox : Canvas
{
#region 成员变量 private VisualCollection controls;
private TextBox textBox;
private ComboBox comboBox;
private ObservableCollection<AutoCompleteEntry> autoCompletionList;
private Timer keypressTimer;
private delegate void TextChangedCallback();
private bool insertText;
private int delayTime;
private int searchThreshold; #endregion 成员变量 #region 构造函数 public AutoCompleteTextBox()
{
controls = new VisualCollection(this);
InitializeComponent(); autoCompletionList = new ObservableCollection<AutoCompleteEntry>();
searchThreshold = ; // default threshold to 2 char
delayTime = ; // set up the key press timer
keypressTimer = new System.Timers.Timer();
keypressTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent); // set up the text box and the combo box
comboBox = new ComboBox();
comboBox.IsSynchronizedWithCurrentItem = true;
comboBox.IsTabStop = false;
Panel.SetZIndex(comboBox, -);
comboBox.SelectionChanged += new SelectionChangedEventHandler(comboBox_SelectionChanged); textBox = new TextBox();
textBox.TextChanged += new TextChangedEventHandler(textBox_TextChanged);
textBox.GotFocus += new RoutedEventHandler(textBox_GotFocus);
textBox.KeyUp += new KeyEventHandler(textBox_KeyUp);
textBox.KeyDown += new KeyEventHandler(textBox_KeyDown);
textBox.VerticalContentAlignment = VerticalAlignment.Center; controls.Add(comboBox);
controls.Add(textBox);
} #endregion 构造函数 #region 成员方法 public string Text
{
get { return textBox.Text; }
set
{
insertText = true;
textBox.Text = value;
}
} public int DelayTime
{
get { return delayTime; }
set { delayTime = value; }
} public int Threshold
{
get { return searchThreshold; }
set { searchThreshold = value; }
} /// <summary>
/// 添加Item
/// </summary>
/// <param name="entry"></param>
public void AddItem(AutoCompleteEntry entry)
{
autoCompletionList.Add(entry);
} /// <summary>
/// 清空Item
/// </summary>
/// <param name="entry"></param>
public void ClearItem()
{
autoCompletionList.Clear();
} private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (null != comboBox.SelectedItem)
{
insertText = true;
ComboBoxItem cbItem = (ComboBoxItem)comboBox.SelectedItem;
textBox.Text = cbItem.Content.ToString();
}
} private void TextChanged()
{
try
{
comboBox.Items.Clear();
if (textBox.Text.Length >= searchThreshold)
{
foreach (AutoCompleteEntry entry in autoCompletionList)
{
foreach (string word in entry.KeywordStrings)
{
if (word.Contains(textBox.Text))
{
ComboBoxItem cbItem = new ComboBoxItem();
cbItem.Content = entry.ToString();
comboBox.Items.Add(cbItem);
break;
}
//if (word.StartsWith(textBox.Text, StringComparison.CurrentCultureIgnoreCase))
//{
// ComboBoxItem cbItem = new ComboBoxItem();
// cbItem.Content = entry.ToString();
// comboBox.Items.Add(cbItem);
// break;
//}
}
}
comboBox.IsDropDownOpen = comboBox.HasItems;
}
else
{
comboBox.IsDropDownOpen = false;
}
}
catch { }
} private void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e)
{
keypressTimer.Stop();
Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
new TextChangedCallback(this.TextChanged));
} private void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
// text was not typed, do nothing and consume the flag
if (insertText == true) insertText = false; // if the delay time is set, delay handling of text changed
else
{
if (delayTime > )
{
keypressTimer.Interval = delayTime;
keypressTimer.Start();
}
else TextChanged();
}
} //获得焦点时
public void textBox_GotFocus(object sender, RoutedEventArgs e)
{
// text was not typed, do nothing and consume the flag
if (insertText == true) insertText = false; // if the delay time is set, delay handling of text changed
else
{
if (delayTime > )
{
keypressTimer.Interval = delayTime;
keypressTimer.Start();
}
else TextChanged();
}
} public void textBox_KeyDown(object sender, KeyEventArgs e)
{
if (textBox.IsInputMethodEnabled == true)
{
comboBox.IsDropDownOpen = false;
}
} /// <summary>
/// 按向下按键时
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void textBox_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Down && comboBox.IsDropDownOpen == true)
{
comboBox.Focus();
}
} protected override Size ArrangeOverride(Size arrangeSize)
{
textBox.Arrange(new Rect(arrangeSize));
comboBox.Arrange(new Rect(arrangeSize));
return base.ArrangeOverride(arrangeSize);
} protected override Visual GetVisualChild(int index)
{
return controls[index];
} protected override int VisualChildrenCount
{
get { return controls.Count; }
} #endregion 成员方法
}
}

4.、使用创建的 AutoCompleteTextbox ,新建一个WPF工程,在Windows1.xaml 中添加自定义的控件,如下:

<Window x:Class="WPFAutoCompleteTextbox.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPFAutoCompleteTextbox"
Title="WPF AutoCompleteTextBox" Height="195" Width="561">
<Grid Background="SteelBlue">
<Button Name="button1" Height="23" Width="75" Margin="12,12,0,0" Click="button1_Click"
         HorizontalAlignment="Left" VerticalAlignment="Top">Clear</Button>
<local:AutoCompleteTextBox Height="23" Width="162" x:Name="textBox1" Margin="25,65,0,0"
          HorizontalAlignment="Left" VerticalAlignment="Top" />
</Grid>
</Window>

5、 在 Windows1.cs 中初始化搜索数据,如下:

    public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
textBox1.AddItem(new AutoCompleteEntry("上海", null));
textBox1.AddItem(new AutoCompleteEntry("北京", null));
textBox1.AddItem(new AutoCompleteEntry("济南", null));
textBox1.AddItem(new AutoCompleteEntry("青岛", null));
textBox1.AddItem(new AutoCompleteEntry("天津", null));
textBox1.AddItem(new AutoCompleteEntry("黑龙江", null));
textBox1.AddItem(new AutoCompleteEntry("聊城", null));
} private void button1_Click(object sender, RoutedEventArgs e)
{
textBox1.Text = string.Empty;
}
}

WPF 之 实现TextBox输入文字后自动弹出数据(类似百度的输入框)的更多相关文章

  1. WPF 禁用TextBox的触摸后自动弹出虚拟键盘

    前言 & 问题 如下截图,TextBox,在触摸点击后,会自动弹出windows的虚拟键盘. 如何,禁用键盘的自动弹出? 调用虚拟键盘 通过调用TapTip.exe或者osk.exe,主动弹出 ...

  2. 微信小程序-输入框输入文字后,将光标移到文字中间,接着输入文字后光标又自动跳到最后

    问题描述: input输入框输入一段文字后,将光标移到文字中间,接着输入文字后光标又自动跳到最后去了. 原因: input事件中,给input框绑定任何事件后,在处理事件时 setData之后就会让光 ...

  3. Layer For Mobile 弹窗 input输入文字后,点击取消确定按钮失效(需点击两次)

    webapp中使用Layer For Mobile弹出弹窗,修改昵称输入文字后,ios手机中,如果不先点击收起键盘,两个按钮点击之后无效... 两个按钮的方法是写在这里的——> 最后只能吧点击按 ...

  4. popupwindow中EditText获取焦点后自动弹出软键盘

    关于popupwindow中EditText获取焦点后自动弹出软键盘的问题,玩过手机qq或空间的童鞋应该知道,再点击评论时会弹出一个编辑框,并且伴随软键盘一起弹出是不是很方便啊,下面我们就来讲一下实现 ...

  5. Windows8连接网络后自动弹出Bing解决方法

    Windows8 网络连接速度很快( ADSL ),但是连接之后总是会打开 Bing,这是很烦人的一件事,因为你连接网络可能并不想打开浏览器,甚至,你讨厌 Bing. 我也一直被这个问题困扰了很久,用 ...

  6. eclipse解压后启动弹出A Java Runtime Evironment(JRE) or Java Development Kit(JDK)....

    系统环境:win7 64bit JDK:jdk-7u79-windows-x64 Eclipse:eclipse-jee-helios-win32 启动eclipse:弹出A Java Runtime ...

  7. iOS webView与js交互在文本空格上输入文字

    项目要求:webview加载html网址,内容为填空题型文本,需要在横线上添加答案,并点击提交按钮后再将答案进行回显 正常加载的效果图片: 这个是用js交互后的效果图: 点击空格,输入想输入的答案,如 ...

  8. Java Swing 如何添加输入文字并且可以滚动的文本框?( JTextArea ,JScrollPane的使用)

    准备: JTextArea 文本区,一个可以输入文字的文本框 常用方法: 1.setText(String t)设置文本区中显示的文本 2.getText() 获取文本区中显示的文本 JScrollP ...

  9. android中实现在矩形框中输入文字,可以显示剩余字数的功能

    虽然这两个功能都比较简单,但是在实际app开发中真的很常见,特别是显示字数或剩余字数这个功能 如下图: 要实现上面的功能,需要做到三点: 1.实现矩形框布局 思路就是矩形框作为整个布局的一个backg ...

随机推荐

  1. eCryptfs文件系统测试

    650) this.width=650;" onclick='window.open("http://blog.51cto.com/viewpic.php?refimg=" ...

  2. ResultMap

    Mybatis 数据库字段和对象属性的映射 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE ...

  3. 排序之希尔排序(shell sort)

    前言 本篇博客是在伍迷兄的博客基础上进行的,其博客地址点击就可以进去,里面好博客很多,我的排序算法都来自于此:一些数据结构方面的概念我就不多阐述了,伍迷兄的博客中都有详细讲解,而我写这些博客只是记录自 ...

  4. mac多版本python安装 pymysql

    系统里面安装了多个python的版本,有2.7和3.4等.默认的2.7版本,但我开发需要3.4版本的. 默认情况下,用pip安装PyMySQL $sudo pip install PyMySQL 安装 ...

  5. CCF 201312-3 最大的矩形 (暴力,离散化)

    问题描述 在横轴上放了n个相邻的矩形,每个矩形的宽度是1,而第i(1 ≤ i ≤ n)个矩形的高度是hi.这n个矩形构成了一个直方图.例如,下图中六个矩形的高度就分别是3, 1, 6, 5, 2, 3 ...

  6. HDU 4596 Yet another end of the world (数学,扩展欧几里德)

    题意:给出n组x,y,z.判断是否存在一个id使得id%x1∈(y1,z1),id%x2∈(y2,z2). 析: 设 id/x1=a , id/x2=b ,则 id-a*x1=u;   (1) id- ...

  7. hdoj 5375 Gray Code

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5375 编码规则:tmp = XOR(gr[i],gr[i-1]); 算是找规律的题目吧,考虑?前后字符 ...

  8. PHP时间格式化封装函数

    /*格式化时间戳为小时,分钟,秒,几天前等 */function dgmdate($timestamp, $format = 'dt', $timeoffset = '9999', $uformat ...

  9. 给js function的参数设置默认值

    C# 中 function func(a,b=1){//具体方法} js 中 function func(a,b){ a= arguments[0] || 10; b= arguments[1] || ...

  10. Visual Studio无法添加断点

    今天在写代码的时候突然发现无法添加断点,更加详细的场景是“按F9可以添加调试行,但是断点不显示,且显示代码行数左边的灰色区域不见了”找了各种方法也没有解决,然后重启.修复甚至重装都不行,最后在万千网页 ...