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. 麒麟OS剽窃

    今年对于我们的IT行业来说可以算是耻辱的一年. 首先是“汉芯丑闻”,上海交大研制了一个所谓的国内第一个完全拥有自主知识产 权的DSP芯片(数字信号微处理器)——“汉芯”,研制人陈进教授以此领取政府一亿 ...

  2. Django 1.6 最佳实践: django项目的服务器自动化部署(转)

    原文:http://www.weiguda.com/blog/41/ 当我们设置服务器时, 不应该每次都使用ssh登录服务器, 再按照记忆一步一步的配置. 因为这样实在是太容易忘记某些步骤了. 服务器 ...

  3. oracle学习 九 游标的使用(持续更)

    为什么要使用? 笔者查阅了一些资料之后得到的结论是, 关系型数据库是面向集合的,而游标是面向行的,游标可对取出来的集合(结果集)中每一行进行相同或不同的操作,还提供对基于游标位置而对表中数据进行删除或 ...

  4. makefile中一些符号的含义

    关于gnu make的详细介绍参看http://www.gnu.org/software/make/manual/make.html   规则 让我们先来粗略地看一看Makefile的规则. targ ...

  5. HDU2897邂逅明下(博弈)

    题目是说每次每个人可以取[p,q],而且是最后一个不得不取完的人输 这道题刚刚看别人过,还一直纠结感觉不会做,然后想到1+q的倍数,还是不会,想到p+q的倍数,却发现最后一个取的人是输的,然后就更加无 ...

  6. C# JackLib系列之GdiHelper圆角矩形的快速生成

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.D ...

  7. DNS与DNS劫持原理、IP、域名、服务器访问浅讲

    我们都知道,平常我们所访问的网站,都是与服务器进行数据交互的.但是,浏览器和服务器是分处于不同的计算机上的,那他们是怎样进行通信的呢?今天,我们就来粗浅地聊一聊.不涉及很深的技术原理,只讲大概的流程. ...

  8. A*算法为什么是最优的

    图搜索的A*算法有两种情况: hn是可采纳的,但是不是满足一致性 如果满足一致性,A*算法的实现要简单一些:即使不检查closed节点的状态重复,也能得到最优的结果 下面是证明最优性的一些关键点: 1 ...

  9. (剑指Offer)面试题18:树的子结构

    题目: 输入两棵二叉树A和B,判断B是不是A的子结构. 二叉树结构定义如下: struct TreeNode{ int val; TreeNode* left; TreeNode* right; }; ...

  10. FTP远程命令集

    使用ftp命令进行远程文件传输 ftp命令是标准的文件传输协议的用户接口.ftp是在TCP/IP网络上的计算机之间传输文件的简单有效的方法.它允许用户传输ASCII文件和二进制文件. 在ftp会话过程 ...