原文:WPF Toolkit AutoCompleteBox 实体类绑定 关键字自定义关联搜索匹配

WPF Toolkit AutoCompleteBox 实体类绑定 关键字自定义关联搜索匹配

网上的例子都是零散的   翻阅了 很多篇文章后 再根据 自己项目的实际需求  整理出一个完整的 应用例子

汉字首字母全文匹配

提取绑定实体类相应的ID值

XAML

<Window
x:Class="WpfApp3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp3"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="800"
Height="450"
mc:Ignorable="d">
<Grid>
<controls:AutoCompleteBox
Name="autoCompleteBox1"
Width="278"
Margin="0,24,0,345"
HorizontalAlignment="Left"
ItemsSource="{Binding}">
<controls:AutoCompleteBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=Name}" />
</StackPanel>
</DataTemplate>
</controls:AutoCompleteBox.ItemTemplate>
</controls:AutoCompleteBox>
<Button
Name="button1"
Width="75"
Height="23"
Margin="92,126,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Click="button1_Click"
Content="Button" />
</Grid>
</Window>

C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using Utility; namespace WpfApp3
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
/// <summary>
/// 构造函数
/// </summary>
public MainWindow()
{
InitializeComponent();
this.Loaded += Window_Loaded;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
List<CityEntity> cityEntity = new List<CityEntity>() {
new CityEntity(,"北京",""),
new CityEntity(,"上海",""),
new CityEntity(,"天津",""),
new CityEntity(,"重庆",""),
new CityEntity(,"北海",""),
new CityEntity(,"香港","")
};
//投影出 CityEntity 实体类的 ID,Name 字段信息
var v = from lp in cityEntity
select new
{
lp.ID,
lp.Name
};
autoCompleteBox1.DataContext = v.ToList();
//AutoCompleteBox 要显示的字段名
autoCompleteBox1.ValueMemberPath = "Name";
//当输入字符后延迟多少毫秒开始进行匹配,默认0
autoCompleteBox1.MinimumPopulateDelay = ;
//最小输入的字符长度,当输入大于等于此长度时,才进行匹配,默认1
autoCompleteBox1.MinimumPrefixLength = ;
//自定义匹配的模式,如果要实现自已的匹配方法,一定要设置为Custom,已预置了约13种方法
autoCompleteBox1.FilterMode = AutoCompleteFilterMode.Custom;
//填充前事件 动态赋值填充数据源数据 在这里编写
autoCompleteBox1.Populating += new PopulatingEventHandler(autoCompleteBox1_Populating);
//填充匹配操作 比如用汉字首字母匹配汉字 在这里编写代码
autoCompleteBox1.ItemFilter += ItemFilter;
}
void autoCompleteBox1_Populating(object sender, PopulatingEventArgs e)
{
e.Cancel = true;//一定要指定已处理此处理,取消此事件
//根据用户输入的字符串 动态从数据库中 提取相匹配的数据
List<CityEntity> cityEntity = new List<CityEntity>() {
new CityEntity(,"北京1",""),
new CityEntity(,"北京2",""),
new CityEntity(,"北京3",""),
new CityEntity(,"北京4","")
};
var v = from lp in cityEntity
select new { lp.ID, lp.Name };
autoCompleteBox1.DataContext = v.ToList();
autoCompleteBox1.ValueMemberPath = "Name";
autoCompleteBox1.PopulateComplete();//一定要指定填充完成,可以进行匹配操作,从而自动引发ItemFilter 事件
}
public bool ItemFilter(string search, object item)
{
//search 就是用户输入的关键字。
//item是就ItemSource中的项,本例是(object(string)),也可以复杂类型,但要求实现IEnumerable接口
//可以根据相应的逻辑再做进一步处理。为提高性能就在填充前对数据源作处理,此处仅为演示。
//要匹配的文本信息
string tbText = GetPropertyValue(item, "Name").ToString().ToLower();
//原文本再拼接原文本的首字
tbText = tbText + GetFirstLetter(tbText).ToLower();
//搜索匹配关键字
if (tbText.Contains(search.ToLower()))
{
return true;//返回True表示此项匹配,会出现在下拉选框中
}
return false;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
if (autoCompleteBox1.SelectedItem != null)
{
//返回SelectedItem绑定的对象信息
object ci = (object)autoCompleteBox1.SelectedItem;
//输出绑定对象的ID信息
MessageBox.Show("您选中的内容ID是---" + GetPropertyValue(ci, "ID").ToString());
}
}
////微软的转换方法 比较简洁 //工具包下载地址http://www.microsoft.com/zh-cn/download/details.aspx?id=15251
////using Microsoft.International.Converters.PinYinConverter;
////using Microsoft.International.Converters.TraditionalChineseToSimplifiedConverter;
///// <summary>
///// 获取汉字首字母
///// </summary>
///// <param name="str"></param>
///// <returns></returns>
//public static string GetPinYinInitial(string str)
//{
// string r = string.Empty;
// foreach (char obj in str)
// {
// try
// {
// ChineseChar chineseChar = new ChineseChar(obj);
// string t = chineseChar.Pinyins[0].ToString();
// r += t.Substring(0, 1);
// }
// catch
// {
// r += obj.ToString();
// }
// }
// return r;
//}
#region 取中文首字母
public static string GetFirstLetter(string paramChinese)
{
string strTemp = "";
int iLen = paramChinese.Length;
int i = ;
for (i = ; i <= iLen - ; i++)
{
strTemp += GetCharSpellCode(paramChinese.Substring(i, ));
}
return strTemp;
}
/// <summary>
/// 得到一个汉字的拼音第一个字母,如果是一个英文字母则直接返回大写字母
/// </summary>
/// <param name="CnChar">单个汉字</param>
/// <returns>单个大写字母</returns>
private static string GetCharSpellCode(string paramChar)
{
long iCnChar;
byte[] ZW = System.Text.Encoding.Default.GetBytes(paramChar);
//如果是字母,则直接返回
if (ZW.Length == )
{
return paramChar.ToUpper();
}
else
{
// get the array of byte from the single char
int i1 = (short)(ZW[]);
int i2 = (short)(ZW[]);
iCnChar = i1 * + i2;
}
//expresstion
//table of the constant list
// 'A'; //45217..45252
// 'B'; //45253..45760
// 'C'; //45761..46317
// 'D'; //46318..46825
// 'E'; //46826..47009
// 'F'; //47010..47296
// 'G'; //47297..47613
// 'H'; //47614..48118
// 'J'; //48119..49061
// 'K'; //49062..49323
// 'L'; //49324..49895
// 'M'; //49896..50370
// 'N'; //50371..50613
// 'O'; //50614..50621
// 'P'; //50622..50905
// 'Q'; //50906..51386
// 'R'; //51387..51445
// 'S'; //51446..52217
// 'T'; //52218..52697
//没有U,V
// 'W'; //52698..52979
// 'X'; //52980..53640
// 'Y'; //53689..54480
// 'Z'; //54481..55289
// iCnChar match the constant
if ((iCnChar >= ) && (iCnChar <= ))
{
return "A";
}
else if ((iCnChar >= ) && (iCnChar <= ))
{
return "B";
}
else if ((iCnChar >= ) && (iCnChar <= ))
{
return "C";
}
else if ((iCnChar >= ) && (iCnChar <= ))
{
return "D";
}
else if ((iCnChar >= ) && (iCnChar <= ))
{
return "E";
}
else if ((iCnChar >= ) && (iCnChar <= ))
{
return "F";
}
else if ((iCnChar >= ) && (iCnChar <= ))
{
return "G";
}
else if ((iCnChar >= ) && (iCnChar <= ))
{
return "H";
}
else if ((iCnChar >= ) && (iCnChar <= ))
{
return "J";
}
else if ((iCnChar >= ) && (iCnChar <= ))
{
return "K";
}
else if ((iCnChar >= ) && (iCnChar <= ))
{
return "L";
}
else if ((iCnChar >= ) && (iCnChar <= ))
{
return "M";
}
else if ((iCnChar >= ) && (iCnChar <= ))
{
return "N";
}
else if ((iCnChar >= ) && (iCnChar <= ))
{
return "O";
}
else if ((iCnChar >= ) && (iCnChar <= ))
{
return "P";
}
else if ((iCnChar >= ) && (iCnChar <= ))
{
return "Q";
}
else if ((iCnChar >= ) && (iCnChar <= ))
{
return "R";
}
else if ((iCnChar >= ) && (iCnChar <= ))
{
return "S";
}
else if ((iCnChar >= ) && (iCnChar <= ))
{
return "T";
}
else if ((iCnChar >= ) && (iCnChar <= ))
{
return "W";
}
else if ((iCnChar >= ) && (iCnChar <= ))
{
return "X";
}
else if ((iCnChar >= ) && (iCnChar <= ))
{
return "Y";
}
else if ((iCnChar >= ) && (iCnChar <= ))
{
return "Z";
}
else return ("?");
}
#endregion
/// <summary>
/// 获取一个类指定的属性值
/// </summary>
/// <param name="info">object对象</param>
/// <param name="field">属性名称</param>
/// <returns></returns>
public static object GetPropertyValue(object info, string field)
{
if (info == null) return null;
Type t = info.GetType();
IEnumerable<System.Reflection.PropertyInfo> property = from pi in t.GetProperties() where pi.Name.ToLower() == field.ToLower() select pi;
return property.First().GetValue(info, null);
}
/// <summary>
/// 城市实体类
/// </summary>
public class CityEntity
{
/// <summary>
/// 城市ID
/// </summary>
public int ID { get; set; }
/// <summary>
/// 城市名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 城市编号
/// </summary>
public string Code { get; set; }
/// <summary>
/// 城市实体类构造函数
/// </summary>
/// <param name="id">城市ID</param>
/// <param name="name">城市名称</param>
/// <param name="code">城市编号</param>
public CityEntity(int id, string name, string code)
{
ID = id;
Name = name;
Code = code;
}
}
}
}
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls; namespace JiaXinTech.WPF.HotelTerminal
{
/// <summary>
/// Test3.xaml 的交互逻辑
/// </summary>
public partial class Test3 : Window
{
public Test3()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
List<CityEntity> cityEntity = new List<CityEntity>() {
new CityEntity(,"北京",""),
new CityEntity(,"上海",""),
new CityEntity(,"天津",""),
new CityEntity(,"重庆",""),
new CityEntity(,"北海",""),
new CityEntity(,"香港","")
}; //投影出 CityEntity 实体类的 ID,Name 字段信息
var v = from lp in cityEntity
select new { lp.ID, lp.Name }; autoCompleteBox1.DataContext = v.ToList();
//AutoCompleteBox 要显示的字段名
autoCompleteBox1.ValueMemberPath = "Name"; //当输入字符后延迟多少毫秒开始进行匹配,默认0
autoCompleteBox1.MinimumPopulateDelay = ;
//最小输入的字符长度,当输入大于等于此长度时,才进行匹配,默认1
autoCompleteBox1.MinimumPrefixLength = ;
//自定义匹配的模式,如果要实现自已的匹配方法,一定要设置为Custom,已预置了约13种方法
autoCompleteBox1.FilterMode = AutoCompleteFilterMode.Custom;
//填充前事件 动态赋值填充数据源数据 在这里编写
autoCompleteBox1.Populating += new PopulatingEventHandler(autoCompleteBox1_Populating);
//填充匹配操作 比如用汉字首字母匹配汉字 在这里编写代码
autoCompleteBox1.ItemFilter += ItemFilter; } void autoCompleteBox1_Populating(object sender, PopulatingEventArgs e)
{
e.Cancel = true;//一定要指定已处理此处理,取消此事件 //根据用户输入的字符串 动态从数据库中 提取相匹配的数据
List<CityEntity> cityEntity = new List<CityEntity>() {
new CityEntity(,"北京1",""),
new CityEntity(,"北京2",""),
new CityEntity(,"北京3",""),
new CityEntity(,"北京4","")
}; var v = from lp in cityEntity
select new { lp.ID, lp.Name }; autoCompleteBox1.DataContext = v.ToList();
autoCompleteBox1.ValueMemberPath = "Name"; autoCompleteBox1.PopulateComplete();//一定要指定填充完成,可以进行匹配操作,从而自动引发ItemFilter 事件 } public bool ItemFilter(string search, object item)
{
//search 就是用户输入的关键字。
//item是就ItemSource中的项,本例是(object(string)),也可以复杂类型,但要求实现IEnumerable接口
//可以根据相应的逻辑再做进一步处理。为提高性能就在填充前对数据源作处理,此处仅为演示。 //要匹配的文本信息
string tbText = GetPropertyValue(item, "Name").ToString().ToLower(); //原文本再拼接原文本的首字
tbText = tbText + GetFirstLetter(tbText).ToLower(); //搜索匹配关键字
if (tbText.Contains(search.ToLower()))
{
return true;//返回True表示此项匹配,会出现在下拉选框中
}
return false;
} private void button1_Click(object sender, RoutedEventArgs e)
{
if (autoCompleteBox1.SelectedItem != null)
{
//返回SelectedItem绑定的对象信息
object ci = (object)autoCompleteBox1.SelectedItem; //输出绑定对象的ID信息
MessageBox.Show("您选中的内容ID是---" + GetPropertyValue(ci, "ID").ToString()); }
} ////微软的转换方法 比较简洁 //工具包下载地址http://www.microsoft.com/zh-cn/download/details.aspx?id=15251
////using Microsoft.International.Converters.PinYinConverter;
////using Microsoft.International.Converters.TraditionalChineseToSimplifiedConverter;
///// <summary>
///// 获取汉字首字母
///// </summary>
///// <param name="str"></param>
///// <returns></returns>
//public static string GetPinYinInitial(string str)
//{
// string r = string.Empty;
// foreach (char obj in str)
// {
// try
// {
// ChineseChar chineseChar = new ChineseChar(obj);
// string t = chineseChar.Pinyins[0].ToString();
// r += t.Substring(0, 1);
// }
// catch
// {
// r += obj.ToString();
// }
// }
// return r; //} #region 取中文首字母 public static string GetFirstLetter(string paramChinese)
{ string strTemp = ""; int iLen = paramChinese.Length; int i = ; for (i = ; i <= iLen - ; i++)
{ strTemp += GetCharSpellCode(paramChinese.Substring(i, )); } return strTemp; } /// <summary> /// 得到一个汉字的拼音第一个字母,如果是一个英文字母则直接返回大写字母 /// </summary> /// <param name="CnChar">单个汉字</param> /// <returns>单个大写字母</returns> private static string GetCharSpellCode(string paramChar)
{ long iCnChar; byte[] ZW = System.Text.Encoding.Default.GetBytes(paramChar); //如果是字母,则直接返回 if (ZW.Length == )
{
return paramChar.ToUpper(); } else
{ // get the array of byte from the single char int i1 = (short)(ZW[]); int i2 = (short)(ZW[]); iCnChar = i1 * + i2; } //expresstion //table of the constant list // 'A'; //45217..45252 // 'B'; //45253..45760 // 'C'; //45761..46317 // 'D'; //46318..46825 // 'E'; //46826..47009 // 'F'; //47010..47296 // 'G'; //47297..47613 // 'H'; //47614..48118 // 'J'; //48119..49061 // 'K'; //49062..49323 // 'L'; //49324..49895 // 'M'; //49896..50370 // 'N'; //50371..50613 // 'O'; //50614..50621 // 'P'; //50622..50905 // 'Q'; //50906..51386 // 'R'; //51387..51445 // 'S'; //51446..52217 // 'T'; //52218..52697 //没有U,V // 'W'; //52698..52979 // 'X'; //52980..53640 // 'Y'; //53689..54480 // 'Z'; //54481..55289 // iCnChar match the constant if ((iCnChar >= ) && (iCnChar <= ))
{ return "A"; } else if ((iCnChar >= ) && (iCnChar <= ))
{ return "B"; } else if ((iCnChar >= ) && (iCnChar <= ))
{ return "C"; } else if ((iCnChar >= ) && (iCnChar <= ))
{ return "D"; } else if ((iCnChar >= ) && (iCnChar <= ))
{ return "E"; } else if ((iCnChar >= ) && (iCnChar <= ))
{ return "F"; } else if ((iCnChar >= ) && (iCnChar <= ))
{ return "G"; } else if ((iCnChar >= ) && (iCnChar <= ))
{ return "H"; } else if ((iCnChar >= ) && (iCnChar <= ))
{ return "J"; } else if ((iCnChar >= ) && (iCnChar <= ))
{
return "K"; } else if ((iCnChar >= ) && (iCnChar <= ))
{ return "L"; } else if ((iCnChar >= ) && (iCnChar <= ))
{ return "M"; } else if ((iCnChar >= ) && (iCnChar <= ))
{ return "N"; } else if ((iCnChar >= ) && (iCnChar <= ))
{ return "O"; } else if ((iCnChar >= ) && (iCnChar <= ))
{ return "P"; } else if ((iCnChar >= ) && (iCnChar <= ))
{ return "Q"; } else if ((iCnChar >= ) && (iCnChar <= ))
{ return "R"; } else if ((iCnChar >= ) && (iCnChar <= ))
{ return "S"; } else if ((iCnChar >= ) && (iCnChar <= ))
{ return "T"; } else if ((iCnChar >= ) && (iCnChar <= ))
{ return "W"; } else if ((iCnChar >= ) && (iCnChar <= ))
{ return "X"; } else if ((iCnChar >= ) && (iCnChar <= ))
{ return "Y"; } else if ((iCnChar >= ) && (iCnChar <= ))
{ return "Z";
}
else return ("?"); } #endregion /// <summary>
/// 获取一个类指定的属性值
/// </summary>
/// <param name="info">object对象</param>
/// <param name="field">属性名称</param>
/// <returns></returns>
public static object GetPropertyValue(object info, string field)
{
if (info == null) return null;
Type t = info.GetType();
IEnumerable<System.Reflection.PropertyInfo> property = from pi in t.GetProperties() where pi.Name.ToLower() == field.ToLower() select pi;
return property.First().GetValue(info, null);
} /// <summary>
/// 城市实体类
/// </summary>
public class CityEntity
{
/// <summary>
/// 城市ID
/// </summary>
public int ID { get; set; }
/// <summary>
/// 城市名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 城市编号
/// </summary>
public string Code { get; set; } /// <summary>
/// 城市实体类构造函数
/// </summary>
/// <param name="id">城市ID</param>
/// <param name="name">城市名称</param>
/// <param name="code">城市编号</param>
public CityEntity(int id, string name, string code)
{
ID = id;
Name = name;
Code = code;
}
}
} }

WPF Toolkit AutoCompleteBox 实体类绑定 关键字自定义关联搜索匹配的更多相关文章

  1. WPF中Image控件绑定到自定义类属性

    首先我们定义一个Student类,有ID,Name,Photo(保存图片路径). using System; using System.Collections.Generic; using Syste ...

  2. [转]C#反射,根据反射将数据库查询数据和实体类绑定,并未实体类赋值

    本文来自:http://www.cnblogs.com/mrchenzh/archive/2010/05/31/1747937.html /****************************** ...

  3. com.google.gson的SerializedName解决实体类与关键字的重名

    使用google的gson包,解决实体类中字段与java关键字的重名: // 比如 当实体类中有switch关键字时,解决冲突如下 @SerializedName("switch" ...

  4. WPF toolkit AutoCompleteBox

    checked http://www.broculos.net/2014/04/wpf-autocompletebox-autocomplete-text.html#.WGNnq4N95aQ. 1.S ...

  5. 关于spring MVC 绑定json字符串与实体类绑定

    1 如果前台传json字符串,后台用@RequestBody 接收 前端 "content-Type":"application/json", 2  前台用fo ...

  6. WPF——传实体类及绑定实体类属性

    public class User: private string _User; public string User1 { get { return _User; } set { _User = v ...

  7. [转]掌握 ASP.NET 之路:自定义实体类简介 --自定义实体类和DataSet的比较

    转自: http://www.microsoft.com/china/msdn/library/webservices/asp.net/CustEntCls.mspx?mfr=true 发布日期 : ...

  8. 关于mysql下hibernate实体类字段与数据库关键字冲突的问题

    好久没写了,都忘记博客了,趁着现在还在公司,写的东西是经过验证的,不是在家凭记忆力写的,正确率有保障,就说说最近遇到的一件事情吧. 以前一直用的oracle数据库,这次项目我负责的模块所在的系统是用的 ...

  9. 修改tt模板让ADO.NET C# POCO Entity Generator With WCF Support 生成的实体类继承自定义基类

    折腾几天记载一下,由于项目实际需要,从edmx生成的实体类能自动继承自定义的基类,这个基类不是从edmx文件中添加的Entityobject. 利用ADO.NET C# POCO Entity Gen ...

随机推荐

  1. freeswitch 编码协商

    编辑 /usr/local/freeswitch/conf/sip_profiles/internal.xml 添加注释     <param name="inbound-zrtp-p ...

  2. 2、使用Python3爬取美女图片-网站中的妹子自拍一栏

    代码还有待优化,不过目的已经达到了 1.先执行如下代码: #!/usr/bin/env python #-*- coding: utf-8 -*- import urllib import reque ...

  3. python生成器,递归调用

    生成器 什么是生成器:只要在函数体内出现yield关键字,那么再执行函数就不会执行函数代码,会得到一个结果,该结果就是生成器 生成器就是迭代器 yield的功能 yield为我们提供了一种自定义迭代器 ...

  4. 2.安装Cython

    许多科学的Python发行版,例如Anaconda,Enthought Canopy和Sage,捆绑Cython并且不需要设置. 与大多数Python软件不同,Cython需要在系统上存在C编译器.获 ...

  5. fensorflow 安装报错 DEPENDENCY ERROR

    1.错误信息 DEPENDENCY ERROR The target you are trying to run requires an OpenSSL implementation. Your sy ...

  6. Fedora 17 无线网卡配置笔记

    转载:http://www.psichen.com/fedora-17-wifi/ 安装并更新完F17后,在网络选项中没有出现无线网,需要自己安装无线网卡驱动.而F17中默认网卡名称从以前的”eth0 ...

  7. git batch

    git batch 不用每次自己写了:不是特别推荐哦: git add . git commit -m "commit" git push git status

  8. 设计模式入门之代理模式Proxy

    //代理模式定义:为其它对象提供一种代理以控制对这个对象的訪问 //实例:鉴于书中给出的样例不太好.并且有些疑问,所以直接用保护代理作为实例 //要求,一旦订单被创建,仅仅有订单的创建人才干够改动订单 ...

  9. 基于对话框的应用程序,点击button打开一个网页

    核心:使用Webbrowser控件 加入一个新的对话框,右键 Insert ActiveX control,选中 双击对话框生成响应的类(Web).并为webbrowser绑定成员变量(m_Web) ...

  10. 阿里云部署Docker(8)----安装和使用redmine

    安装redmine对过程进行管理. 须要说明的是:当你在docker images的时候,会说没连接到xxxx的时候,并且会提示用"docker -d".事实上这仅仅是把docke ...