65.9K
CodeProject 正在变化。 阅读更多。
Home

WPF 自动完成控件

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.93/5 (14投票s)

2009年12月14日

CPOL

1分钟阅读

viewsIcon

95830

downloadIcon

6623

通过扩展 ComboBox 控件在 WPF 中实现一个自动完成控件。

引言

WPF似乎缺乏对自动完成控件的支持。最接近的是 ComboBox,它是本文实现的基础。

背景

自动完成控件允许用户输入文本,同时根据用户已经输入的内容查询可能的选择。最流行的自动完成实现处理的是对控件中当前文本的“以...开始”的查询。

工作原理

以下是我们关心的 ComboBox 中的一些属性:

  • IsEditable - 这允许用户将文本输入到控件中。
  • StaysOpenOnEdit - 这将强制组合框在键入时保持打开状态。
  • IsTextSearchEnabled - 这使用 ComboBox 的默认“自动完成”行为。

神奇之处

通过结合上述属性(非常容易理解)和一个定时器来控制查询的延迟,一个允许用户附加新的数据源的事件,以及一些样式,我们可以实现一个自动完成控件。

使用控件

XAML

<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>

与组合框类似,自动完成控件利用 DisplayMemberPathSelectValuePath 属性来绑定到特定的数据源。

代码隐藏

/// <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 模式为绑定到数据源的任何实体创建一个 ViewModel,其中包含 HighLight 属性。通过使用样式,这个高亮部分将反映在下拉列表中。

历史

  • 2009年12月14日 - 初始创建。
© . All rights reserved.