2013-07-04 40 views
3

首先,雖然有許多關於使用linq過濾用戶輸入的文本框的observablecollection的問題,但沒有提到運行代碼的時候,它阻止了我輸入用英語。使用linq過濾observablecollection的文本框可以防止英文輸入

爲了解釋我的代碼,我有一個簡單的類Person,帶有2個字符串屬性KName和EName,它們將代表韓文名稱和英文名稱。持有這些人將成爲名爲人員的ObservableCollection。

class Person 
    { 
     public string KName { get; set; } 
     public string EName { get; set; } 
    } 

ObservableCollection<Person> persons; 
    public MainPage() 
    { 
     this.InitializeComponent(); 
     persons = new ObservableCollection<Person>(); 

     Person s = new Person(); 
     s.KName = "홍길동"; 
     s.EName = "Hong Kil-dong"; 
     persons.Add(s); 

     Person t = new Person(); 
     t.KName = "김지영"; 
     t.EName = "Kim Ji-young"; 
     persons.Add(t); 

     Person u = new Person(); 
     u.KName = "최철수"; 
     u.EName = "Choi Chul-soo"; 
     persons.Add(u); 

     this.DataContext = persons; 
    } 

在XAML的一面,我有一個KeyDown事件處理程序的文本框,如果按下Enter鍵,來處理搜索和將顯示一個ListView即會檢查過濾器的結果。

<Page 
    x:Class="TextboxTest.MainPage" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="using:TextboxTest" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d"> 

    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> 
     <TextBox x:Name="SearchTextBox" Height="70" Margin="15" 
       VerticalAlignment="Top" KeyDown="SearchTextBox_Enter"/> 
     <ListView x:Name="SearchResults" Margin="15" Height="500"> 
      <ListView.ItemTemplate> 
       <DataTemplate> 
        <StackPanel Orientation="Horizontal" Margin="5" HorizontalAlignment="Left"> 
         <TextBlock Width="200" Text="{Binding Path=KName}" 
            TextAlignment="Left" HorizontalAlignment="Left" /> 
         <TextBlock Width="200" Text="{Binding Path= EName}" /> 
        </StackPanel> 
       </DataTemplate> 
      </ListView.ItemTemplate> 
     </ListView> 
    </Grid> 
</Page> 

,並在KeyDown處理程序

private void SearchTextBox_Enter(object sender, KeyRoutedEventArgs e) 
    { 
     if (e.Key == Windows.System.VirtualKey.Enter) 
     { 
      string txt = SearchTextBox.Text; 
      if(SearchResults.SelectedItem != null) 
       SearchResults.SelectedItem = null; 

      var filter = from Person in persons 
          let kname = Person.KName 
          let ename = Person.EName 
          where ename.Contains(txt) || 
          kname.Contains(txt) 
          orderby kname 
          select Person; 


      SearchResults.ItemsSource = filter; 
     } 
     e.Handled = true; 
    } 

所以我的問題是,我可以在韓國型,但我不能在文本框中輸入英文。我可以從其他地方複製英文文本,將其粘貼到文本框中,並按預期進行過濾。從文本框中刪除KeyDown處理程序,它將輸入英語罰款。所以問題必須是KeyDown處理程序。有沒有人看到我的代碼有什麼問題?還是有更好的方法去做這件事?

回答

1

您需要修復SearchBoxTextBox_Enter方法。

e.Handled = true; 

必須放在IF-表達的內部,如:

if (e.Key == Windows.System.VirtualKey.Enter) 
{ 
    // filtering... 
    e.Handled = true; 
} 
+0

謝謝!骨頭錯誤 –

相關問題