根据TextBox中输入的文本在ListBox中选择项目

时间:2012-09-06 14:31:21

标签: wpf xaml mvvm

我正在准备一个示例代码,当用户在TextBox中输入文本时,会自动选择ListBox中的文本。到目前为止,我已经实现了结果,但没有不区分大小写的匹配。这是代码。

XAML

<StackPanel>
    <TextBox Name="txt" />
    <ListBox ItemsSource="{Binding Employees}" DisplayMemberPath="Name" SelectedValuePath="Name" 
             Height="100" SelectedValue="{Binding Text, ElementName=txt}" SelectedItem="{Binding SelectedEmployee}"/>
    <Button Content="OK" Command="{Binding SaveCommand}" />
</StackPanel>

我将此XAML与以下ViewModel绑定。

视图模型

public class CheckViewModel : ViewModel.ViewModelBase
{
    IList<Employee> employees;

    Employee _selectedEmployee;

    public CheckViewModel()
    {
        employees = new List<Employee>() { 
            new Employee(1, "Morgan"), 
            new Employee(2, "Ashwin"), 
            new Employee(3, "Shekhar"),
            new Employee(5, "Jack"),
            new Employee(5, "Jill")
        };
    }

    public IList<Employee> Employees
    {
        get
        { return employees; }
    }

    public Employee SelectedEmployee
    {
        get
        { return _selectedEmployee; }
        set
        {
            if (_selectedEmployee != value)
            {
                _selectedEmployee = value;
                this.OnPropertyChanged("SelectedEmployee");
            }
        }
    }

    ICommand _saveCommand;
    public ICommand SaveCommand
    {
        get
        {
            if (_saveCommand == null)
            {
                _saveCommand = new ViewModel.RelayCommand((p) =>
                {
                    if(this._selectedEmployee != null)
                        MessageBox.Show(this._selectedEmployee.Name);
                    else
                        MessageBox.Show("None Selected");
                },
                (p) =>
                {
                    return this._selectedEmployee != null;
                });
            }
            return _saveCommand;
        }
    }
}

public class Employee
{
    public Employee(int id, string name)
    {
        this.Name = name;
        this.Id = id;
    }
    public string Name { get; set; }
    public int Id { get; set; }
}

因此,当我在TextBox中键入“Jack”时,正好会出现选择。但是当我改变案例 - “jack”时 - 选择不会发生,SelectedEmployee变为null。当然,比较区分大小写,但我该如何改变这种行为呢?

您能指导我如何使比较案例不敏感吗?

2 个答案:

答案 0 :(得分:2)

您可以将文本框绑定到ViewModel中的属性,如下所示:

    <TextBox Name="txt" Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}"/>

视图模型:

    public string SearchText
    {
        get { return _searchText; }
        set
        {
            _searchText = value;
            // provide your own search through your collection and set SelectedEmployee
        }
    }

答案 1 :(得分:0)

如果使用HashSet,则可以设置比较器。它还会阻止您输入重复值。

HashSet<string> xxx = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);

不是问题,而是比较两个字符串不区分大小写的用法

String.Compare Method (String, String, Boolean)