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 ...
随机推荐
- F2063 Could not compile used unit 'tt.pas'
install packge error F2063 Could not compile used unit 'tt.pas' 有可能是工程的pas文件相对路径不对.在工程管理看是否能打开文件,如果打 ...
- JSF 2 button and commandButton example
In JSF 2.0, both <h:button /> and <h:commandButton /> tags are used to render HTML input ...
- socket的异步回调函数,采用一问一答
socket.Send(buf); AsyncCallback callback = new AsyncCallback(ReceiveData5); mysocket.BeginReceive(Wi ...
- [Linux]常用命令与目录全拼
命令缩写: ls:list(列出目录内容)cd:Change Directory(改变目录)su:switch user 切换用户rpm:redhat package manager 红帽子打包管理器 ...
- Combox选中项注意事项
一般我们选中某个combox的下拉框会用如下方式: 1.combox.SelectedIndex=下拉框下标,如0是选中第一个.-1是不选中任何项等等: 2.combox.SelectedItem=某 ...
- win10的安装、win10启动盘制作
需要的材料 win10映像 U盘 UltraISO软件 1.下载对应的win10映像 有64位和32位可选(自己找地方下) 2.下载UltraISO软件 3.准备一只U盘,插入电脑 4.启动Ultra ...
- head first-----------adpter pattern
head first-----------------深入浅出适配器模式 适配器模式:将一个类的接口,转换成客户想要的另外一个接口,适配器然原本接口不兼容的类可以合作无间.从而可以不用更改旧 ...
- STM32 DFU -- Device Firmware Upgrade
DFU Class Requests Get Status The Host employs the DFU_GETSTATUS request to facilitate synchronizati ...
- Hex-Rays decompiler type definitions and convenience macros
/****************************************************************************************** Copyrigh ...
- uva129 - Krypton Factor 7.4.3 困难的串
7.4.3困难的串 学习点:dfs加入返回值,递归搜索过程中如果有一个成功,就直接退出 //7.4.3 困难的串 #include<cstdio> #include<cstrin ...