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. cordova,phonegap 重力感应

    3.0版本后,cordova通过插件模式实现设备API,使用CLI的plugin命令可以添加或者移除插件: $ cordova plugin add org.apache.cordova.device ...

  2. 前端复习-02-ajax原生以及jq和跨域方面的应用。

    ajax这块我以前一直都是用现成的jq封装好的东西,而且并没有深入浅出的研究过,也没有使用过原生形式的实现.包括了解jsonp和跨域的相关概念但是依然没有实现过,其中有一个重要的原因我认为是我当时并不 ...

  3. Spark的任务处理流程

    持续推送....

  4. 思科ASA系列防火墙配置手册

    使用console连接线登录方法 1.使用cisco的console连接线,连接设备的console口和计算机com口(笔记本用USB转COM口连接线)2.使用超级终端或secureCRT软件连接设备 ...

  5. ]用EnumChildWindows遍历窗口的方法

    最近项目有需要,得到一个非自己实现的窗口控件对象.于是想起曾经做过类似功能.总结如下: 调用EnumChildWindows(this->m_hWnd, EnumChildProc, NULL) ...

  6. C#核心基础--类(2)

    C#核心基础--类的声明 类是使用关键字 class 声明的,如下面的示例所示: 访问修饰符 class 类名 { //类成员: // Methods, properties, fields, eve ...

  7. Linux下Hadoop集群环境的安装配置

    1)安装Ubuntu或其他Linux系统: a)为减少错误,集群中的主机最好安装同一版本的Linux系统,我的是Ubuntu12.04. b)每个主机的登陆用户名也最好都一样,比如都是hadoop,不 ...

  8. SharePoint 2013 自定义翻页显示列表项

    项目需求:自定义开发一个能分页显示列表项的小部件,允许左右翻页,能根据用户权限来显示管理链接等. 效果如下: 技术要求:使用sharepoint rest API 来获取列表项,这样性能高,能够快速响 ...

  9. Mathematics for Computer Graphics数学在计算机图形学中的应用 [转]

    最近严重感觉到数学知识的不足! http://bbs.gameres.com/showthread.asp?threadid=10509 [译]Mathematics for Computer Gra ...

  10. (剑指Offer)面试题25:二叉树中和为某一值的路径

    题目: 输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径.路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径. 二叉树结点的定义: struct TreeNode ...