WPF:AutoCompleteBox,一个自动完成的文本框

这个WPF工具包包括AutoCompleteBox控制室。顾名思义,它是一个自动完成文本框控件。在本文中,我们将展示如何安装工具包以及如何使用AutoCompleteBox。

1、安装WPF工具包

第一步是安装WPF工具包。你可以的下载安装程序或者从VisualStudio中的NuGet包管理器安装它。

Install WPF Toolkit from NuGet
从NuGet安装WPF工具包

2、引用正确的命名空间

AutoCompleteBox位于System.Windows.Controls.Input.Toolkit.dll。必须使用以下命名空间:

xmlns:toolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit"

3、将AutoCompleteBox添加到视图中

假设您有这样一个视图模型:

public interface IYourViewModel
{
    IEnumerable<string> Names { get; }
    string SelectedName { get; set; }
}

然后可以这样添加AutoCompleteBox控件:

<toolkit:AutoCompleteBox   
                        ItemsSource="{Binding Names}"
                        SelectedItem="{Binding SelectedName, Mode=TwoWay}" />

每当选择更改时,SelectedName属性更新。

4、自定义AutoCompleteBox

在自定义用户体验时,您需要查看以下几个有用的属性:

IsTextCompletionEnable:“自动完成”部分。如果启用,将在用户开始键入时自动选择第一个匹配项。
过滤模式*设置自动完成开始,包含,等于。
最小前缀长度在显示任何建议之前所需的最少字符数。

5、在自定义类中使用AutoCompleteBox

现在让我们考虑一下,您希望使用自定义对象而不是字符串集合。

public class Person
{
    public DateTime Birthday { get; set; }
    public string Name { get; set; }
}

视图模型变化不大:

public interface IPeopleViewModel
{
    IEnumerable<Person> People { get; }
    Person SelectedPerson { get; set; }
}

在使用控件时,可以指定ValueMemberPath或者价值绑定属性指示将用于搜索的字段以及文本框部分中的显示字段。

<toolkit:AutoCompleteBox
    ItemsSource="{Binding People}"
    SelectedItem="{Binding SelectedPerson, Mode=TwoWay}"
    ValueMemberPath="Name"
    ItemTemplate="{StaticResource AutoCompleteBoxItemTemplate}" />

因为现在我们正在使用对象,所以我们需要指定一个模板,否则我们需要指定托斯特林对象的方法将用于显示。

<DataTemplate x:Key="AutoCompleteBoxItemTemplate">
    <StackPanel Orientation="Horizontal">
        <Label
            Content="{Binding Name}"
            Width="100" />
        <Label
            Content="{Binding Birthday}"
            FontStyle="Italic"
            Foreground="DarkGray" />
    </StackPanel>
</DataTemplate>

在这个例子中,我们只显示名字和生日。

AutoCompleteBox with custom ItemTemplate
带有自定义ItemTemplate的AutoCompleteBox

6、多字段搜索

现在,您已经知道如何对象使用AutoCompleteBox,但您希望更改进行筛选的方式。您可以通过使用ItemFilter属性,该属性期望AutoCompleteFilterPredicate代表。

假设Person类现在有一个FirstName和LastName属性,并且要在这两个字段中搜索。

public class Person
{
    public DateTime Birthday { get; set; }
    public string Name { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

在视图模型中创建谓词:

public AutoCompleteFilterPredicate<object> PersonFilter
{
    get
    {
        return (searchText, obj) =>
            (obj as Person).FirstName.Contains(searchText)
            || (obj as Person).LastName.Contains(searchText);
    }
}

然后在AutoCompleteBox中设置属性:

<toolkit:AutoCompleteBox
    ItemsSource="{Binding People}"
    SelectedItem="{Binding SelectedPerson, Mode=TwoWay}"
    ValueMemberPath="Name"
    ItemTemplate="{StaticResource AutoCompleteBoxItemTemplate}"
    ItemFilter="{Binding PersonFilter}" />

猜你喜欢

转载自blog.csdn.net/cxb2011/article/details/89923011