WPF 之 实现TextBox输入文字后自动弹出数据(类似百度的输入框)
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输入文字后自动弹出数据(类似百度的输入框)的更多相关文章
- WPF 禁用TextBox的触摸后自动弹出虚拟键盘
前言 & 问题 如下截图,TextBox,在触摸点击后,会自动弹出windows的虚拟键盘. 如何,禁用键盘的自动弹出? 调用虚拟键盘 通过调用TapTip.exe或者osk.exe,主动弹出 ...
- 微信小程序-输入框输入文字后,将光标移到文字中间,接着输入文字后光标又自动跳到最后
问题描述: input输入框输入一段文字后,将光标移到文字中间,接着输入文字后光标又自动跳到最后去了. 原因: input事件中,给input框绑定任何事件后,在处理事件时 setData之后就会让光 ...
- Layer For Mobile 弹窗 input输入文字后,点击取消确定按钮失效(需点击两次)
webapp中使用Layer For Mobile弹出弹窗,修改昵称输入文字后,ios手机中,如果不先点击收起键盘,两个按钮点击之后无效... 两个按钮的方法是写在这里的——> 最后只能吧点击按 ...
- popupwindow中EditText获取焦点后自动弹出软键盘
关于popupwindow中EditText获取焦点后自动弹出软键盘的问题,玩过手机qq或空间的童鞋应该知道,再点击评论时会弹出一个编辑框,并且伴随软键盘一起弹出是不是很方便啊,下面我们就来讲一下实现 ...
- Windows8连接网络后自动弹出Bing解决方法
Windows8 网络连接速度很快( ADSL ),但是连接之后总是会打开 Bing,这是很烦人的一件事,因为你连接网络可能并不想打开浏览器,甚至,你讨厌 Bing. 我也一直被这个问题困扰了很久,用 ...
- 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 ...
- iOS webView与js交互在文本空格上输入文字
项目要求:webview加载html网址,内容为填空题型文本,需要在横线上添加答案,并点击提交按钮后再将答案进行回显 正常加载的效果图片: 这个是用js交互后的效果图: 点击空格,输入想输入的答案,如 ...
- Java Swing 如何添加输入文字并且可以滚动的文本框?( JTextArea ,JScrollPane的使用)
准备: JTextArea 文本区,一个可以输入文字的文本框 常用方法: 1.setText(String t)设置文本区中显示的文本 2.getText() 获取文本区中显示的文本 JScrollP ...
- android中实现在矩形框中输入文字,可以显示剩余字数的功能
虽然这两个功能都比较简单,但是在实际app开发中真的很常见,特别是显示字数或剩余字数这个功能 如下图: 要实现上面的功能,需要做到三点: 1.实现矩形框布局 思路就是矩形框作为整个布局的一个backg ...
随机推荐
- Physicals
[Physicals] The physics simulation in Sprite Kit is performed by adding physics bodies to scenes. [T ...
- vim之pydiction插件
[vim之pydiction插件] It consists of three main files: python_pydiction.vim -- Vim plugin. complete-dict ...
- hdu 1576 A/B (扩展欧几里德简单运用)
http://acm.hdu.edu.cn/showproblem.php?pid=1576 A/B Time Limit: 1000/1000 MS (Java/Others) Memory Lim ...
- C#图解教程读书笔记(第15章 委托)
委托是C#的一个很重要的知识点. 1.什么是委托 委托在我认为,就是一系列格式相同的方法列表,可能就是定义的名称不一致,参数.返回值等都是一样的. 2.如何声明委托 delegate void MyF ...
- C# 消息处理机制及自定义过滤方式
一.消息概述 Windows 下应用程序的执行是通过消息驱动的.消息是整个应用程序的工作引擎,我们需要理解掌握我们使用的编程语言是如何封装消息的原理. 1. 什么是消息(Message) 消息就是通知 ...
- Windows下使用NIF扩展Erlang方法
在Erlang中,NIF(Native Implemented Function)被用来扩展erlang的某些功能,一般用来实现一些erlang很难实现的,或者一些erlang实现效率不高的功能. N ...
- window8家庭版上的RationalRose
来点儿小插曲儿,本是继续Java系列文章的续集的,但是最近要用到UML,在网上看了看,查了查推荐的到是不少,最终还是选择了rose,哈哈,一半是冲着名字去的,一半看看了与其它的UML的比较,最终中意r ...
- tab栏切换的特殊效果(类似网易的登陆栏效果)
代码显示效果如上图所示: 需求说明: 在实际需求中,会遇到这样的情况:不仅是要展示选项卡的内容,而且还有可能在选项卡中需求顾客填写相关内容,而这些内容是顾客如果想了解更深层次的,就会继续填写右边的内容 ...
- xx.exe 中的 0x7c92e4df 处最可能的异常: 0xC0000008: An invalid handle was specified
今天遇到个超级奇怪的问题,昨天还好端端的程序,今天用VS打开后,在关闭主窗口的时候居然弹出错误提示:xx.exe 中的 0x7c92e4df 处最可能的异常: "0xC0000008: An ...
- Flex编程注意之直接获取某个组件的对象(this[]用法)通过id获取控件
有这样一个需求:假如你new了一百次Button,同时这些button的id分别赋值如btn1.id = "button1"; btn2.id = "button2&qu ...