需求分析:现在有表 City( name ,shortName) eg: city:广州 ,GZ ;上海,SH
在AutoCompleteBox 中输入“G”、GZ或“广”、“ 广州”都自动弹出“ 广州”.
实现
1.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<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
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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.图示