使用linq通过文本框过滤observalecollection会阻止英文打字
本文关键字:文打字 observalecollection 过滤 linq 文本 使用 | 更新日期: 2023-09-27 18:21:09
首先,虽然有很多关于使用linq通过用户输入的文本框过滤可观测集合的问题得到了回答,但没有关于运行代码时的问题,它阻止了我用英语打字。
为了解释我的代码,我有一个简单的类Person,它有两个字符串属性KName和EName,它们将代表一个韩语名称和一个英语名称。持有这些人将是一个名为人的可观察集合。
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处理程序上。有人看到我的代码有什么问题吗?或者有更好的方法来做这件事吗?
您需要修复SearchBoxTextBox_Enter方法。
e.Handled = true;
必须放置在IF表达式内部,如:
if (e.Key == Windows.System.VirtualKey.Enter)
{
// filtering...
e.Handled = true;
}