2012-09-06 74 views
0

我正在準備一個示例代碼,其中當用戶在文本框中輸入文本時,自動選擇ListBox中的文本。到目前爲止,我已經達到了結果,但沒有大小寫不匹配的匹配。這是代碼。根據在TextBox中輸入的文本在列表框中選擇項目

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與下面的視圖模型。

視圖模型

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

所以,當我在文本框中鍵入 「傑克」,選擇適時出現。但是,當我更改案例 - 「傑克」 - 選擇不會發生和SelectedEmployee變爲空。當然,比較是區分大小寫的,但我怎麼改變這種行爲呢?

請你指導我如何使比較案例不敏感?如果您使用HashSet的,那麼你可以設置比較器

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

回答

2

您可以將文本框綁定到財產視圖模型如下:

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

視圖模型。它也會阻止你輸入重複值。

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

不是問題,但比較兩個字符串大小寫不敏感的使用

String.Compare Method (String, String, Boolean)

+0

我想知道,如果不區分大小寫的比較是通過分配的任何財產。好的,謝謝你,你的建議有幫助。 – Ritesh

相關問題