这是我的XAML代码。目前,LongListSelector
正在显示两个TextBox
个; City
和Country
。
<DataTemplate x:Key="LongListSelectorItemTemplate">
<ListBoxItem>
<StackPanel Name="Address">
<TextBlock Name="city" Text = "{Binding City}" />
<TextBlock Name="country" Text="{Binding Country}"/>
</StackPanel>
</ListBoxItem>
</DataTemplate>
<TextBox Name="search"/>
有一个SearchBox
,根据搜索文字,我需要突出显示LongListSelector
中的文字,然后过滤掉任何其他内容。这正是People / PhoneBook应用程序在设备中的工作方式。
我设法突出显示/过滤工作,然而,在以下情况下,项目的顺序变得非常随机:
London UK Delhi India NY US Paris France
突出显示后,它变为:
London India Paris US ...
到目前为止,这是我的C#代码:
void searchResults() {
var filtereBlocks = RecurseChildren<StackPanel>(ListSelector)
.Where(n => n.Name == "Address").ToList();
foreach (var container in filtereBlocks) {
bool ret1, ret2;
TextBlock city = container.Children[0] as TextBlock,
country = container.Children[1] as TextBlock;
ret1 = Highlight(ref city, search.text);
ret2 = Highlight(ref country, search.text);
if (!ret1 && !ret2) {
city.visibility = System.Windows.Visibility.Collapsed;
country.visibility = System.Windows.Visibility.Collapsed;
}
}
}
// Found on the Internet
IEnumerable<T> RecurseChildren<T>(DependencyObject root) where T : UIElement {
if (root is T) {
yield return root as T;
}
if (root != null) {
var count = VisualTreeHelper.GetChildrenCount(root);
for (var idx = 0; idx < count; idx++) {
foreach (var child in RecurseChildren<T>(VisualTreeHelper.GetChild(root, idx))) {
yield return child;
}
}
}
}