Silverlight之AutoCompleteBox自定义过滤ItemFilter

需求分析:现在有表 City( name ,shortName)  eg: city:广州 ,GZ ;上海,SH

 

在AutoCompleteBox 中输入“G”、GZ或“广”、“ 广州”都自动弹出“ 广州”.

 

实现

 

1.

xaml代码
   
   
< UserControl xmlns:input ="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input" x:Class ="SilverlightAutoComboxNameOrShortName.MainPage"
xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d
="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc ="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable
="d" d:DesignWidth ="640" d:DesignHeight ="480" >
< Grid x:Name ="LayoutRoot" >
< input:AutoCompleteBox FilterMode ="Custom" x:Name ="acb" Width ="150" Height ="30" ></ input:AutoCompleteBox >
</ Grid >
</ UserControl >

 

 

2.city类 ,并重写Tostring 方法

 

  
  
public class City
{
public string Name { get ; set ; }
public string ShortName { get ; set ; }

public override string ToString() { return Name; }

}

 

 

3.mainpage

 

 

代码
   
   
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
this .Loaded += new RoutedEventHandler(MainPage_Loaded);
}

void MainPage_Loaded( object sender, RoutedEventArgs e)
{
// 为AutoCompleteBox提供数据源
acb.ItemsSource = GetCities();

// 过滤模式为自定义

// 自定义过滤条件
acb.ItemFilter = (search, item) =>
{
City city
= item as City;
if (city != null )
{
string filter = search.ToLower();
// 包含filter返回true
return city.Name.Contains(filter) ||
city.ShortName.ToLower().Contains(filter);
}
return false ;
};
}

List
< City > GetCities()
{
List
< City > cs = new List < City > ();
cs.Add(
new City { Name = " 广州 " , ShortName = " GZ " });
cs.Add(
new City { Name = " 南京 " , ShortName = " NJ " });
cs.Add(
new City { Name = " 上海 " , ShortName = " SH " });
cs.Add(
new City { Name = " 北京 " , ShortName = " BJ " });
cs.Add(
new City { Name = " 扬州 " , ShortName = " YZ " });
cs.Add(
new City { Name = " 杭州 " , ShortName = " HZ " });
return cs;
}

}

 

 

4.图示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值