[英]How do you implement custom inline searching in an ItemsControl?
這是兩部分的。
首先,在WPF中,標准的ListBox控件自動支持對其項進行內聯搜索。 它通過使用項目的ToString函數來完成此操作,這意味着如果您將焦點放在列表框中並開始輸入,它將進行最左側的搜索,突出顯示ToString與您鍵入的內容匹配的所有項目。 短時間內的后續按鍵操作將添加到搜索字符串中(即,鍵入“ A”后跟“ S”將向左搜索“ AS”,而鍵入“ A”然后暫停,然后鍵入“ S”將向左搜索-搜索“ S”。
問題在於這種機制似乎完全依賴於ToString返回的值,在某些情況下,這是我們不能依靠的。 還有其他可以代替ToString使用的東西嗎?
第二部分是,行為似乎只出現在ListBox中,但是沒有其他ItemsControl對象(或像TreeView這樣的層次結構對象)。不必從頭開始重寫該功能,是否有簡單的方法添加它到ItemsControl?
您可以控制使用TextSearch.Text
或TextSearch.TextPath
附加屬性TextSearch.TextPath
。 (請參閱http://msdn.microsoft.com/zh-cn/library/system.windows.controls.textsearch(v=vs.110).aspx )
您可以將TextSearch.TextPath
應用於ListBox
實例(以便搜索此屬性而不是ToString
),也可以將TextSearch.Text
應用於單個ListBoxItem
子項(以便為單個元素設置單獨的搜索文本)。
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.Resources>
<XmlDataProvider x:Key="Items" XPath="People">
<x:XData>
<People xmlns="">
<Person Name="John" Surname="Smith" />
<Person Name="Andrew" Surname="Johnson" />
<Person Name="Otis" Surname="Everett" />
<Person Name="Jesus" Surname="Osborn" />
</People>
</x:XData>
</XmlDataProvider>
</Window.Resources>
<StackPanel>
<TextBlock Text="Searches by a property (Name):" />
<ListBox ItemsSource="{Binding Source={StaticResource Items}, XPath=*}"
TextSearch.TextPath="@Name">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock>
<Run Text="{Binding XPath=@Name}" /> <Run Text="{Binding XPath=@Surname}" />
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<TextBlock>Searches by a individual value (number in english):</TextBlock>
<ListBox>
<ListBoxItem TextSearch.Text="One">1</ListBoxItem>
<ListBoxItem TextSearch.Text="Two">2</ListBoxItem>
<ListBoxItem TextSearch.Text="Three">3</ListBoxItem>
<ListBoxItem TextSearch.Text="Four">4</ListBoxItem>
</ListBox>
</StackPanel>
</Window>
此行為在ItemsControl
類中實現(您可以通過搜索找到ItemsControl
后代的其他示例: ComboBox
, DataGrid
)。 您可以將IsTextSearchEnabled
屬性設置為true以使其起作用。 (請參閱http://msdn.microsoft.com/zh-cn/library/system.windows.controls.itemscontrol.istextsearchenabled(v=vs.110).aspx )
單級搜索適用於TreeView
。 我想如果要執行多級搜索,應該以編程方式實現搜索。 (請參閱http://social.msdn.microsoft.com/Forums/vstudio/en-US/e6d58fcc-4eaa-4bdc-8621-ce24c8efd330/treeview-textsearch )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.