代碼:/Files/zhuqil/AutoComplete.zip
介紹:
在WPF中缺少一個支援自動完成的控制項,最接近的控制項是ComboBox ,它也是實現本篇文章的一個基礎控制項。
背景:
一個自動完成控制項允許使用者輸入文本的時候,控制項會儘可能的去查詢出一個使用者已經輸入的文本選擇項。最流行的自動完成處理是通過查詢這個控制項當前文本的開頭部分。
它是如何運作:
下面是我們關心的一些ComboBox中的屬性:
IsEditable- 這個允許使用者在這個控制項上輸入文本。
StaysOpenOnEdit - 這個將強制ComboBox在輸入時保持開啟。
IsTextSearchEnabled - 這將使用ComboBox預設的自動完成的行為。
我們通過使用上面的屬性結合一個控制延遲查詢的時間,和允許使用者附加新的資料來源的事件,以及一些風格樣式,來實現自動完成控制項。(AutoComplete.xaml.cs檔案中)
使用這個控制項
<Window x:Class="Gui.TestWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ctr="clr-namespace:Gui.Controls"
Title="Auto Complete Test"
Height="200" Width="300"
Loaded="Window_Loaded">
<StackPanel>
<StackPanel.Resources>
<ResourceDictionary
Source="/Gui.Controls;component/Styles/AutoComplete.Styles.xaml" />
</StackPanel.Resources>
<Label>Cities:</Label>
<ctr:AutoComplete x:Name="autoCities"
SelectedValuePath="CityID" DisplayMemberPath="Name"
PatternChanged="autoCities_PatternChanged"
Style="{StaticResource AutoCompleteComboBox}"
Delay="500"/>
<!-- can also do binding on selected value -->
</StackPanel>
</Window>
類似一個combobox,自動完成控制項利用DisplayMemberPath 和SelectValuePath 屬性來綁定具體的資料來源
/// <summary>
/// occurs when the user stops typing after a delayed timespan
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
protected void autoCities_PatternChanged(object sender,
Gui.Controls.AutoComplete.AutoCompleteArgs args)
{
//check
if (string.IsNullOrEmpty(args.Pattern))
args.CancelBinding = true;
else
args.DataSource = TestWindow.GetCities(args.Pattern);
}
我們能利用PatternChanged事件來監聽控制項上當前輸入資料的改變。
有趣的地方:
利用MVVM模式能建立一個任何實體的視圖模型,並將其綁定到具有突顯屬性的資料來源上。通過使用樣式,這突顯的部分將顯示在下拉框中。
說明:
代碼很簡單,很容易看懂。有任何問題請提出來改正,謝謝!紅色部分是自己加的。
原文連結:http://www.codeproject.com/KB/WPF/WPF_Autocomplete.aspx