在列表框中选择在WPF中搜索的项目
本文关键字:项目 搜索 选择 列表 WPF | 更新日期: 2023-09-27 18:05:46
如何通过向文本框插入文本来选择列表框中的项目?
我控制了两个元素:ListBox
包含用于搜索的对象,TextBox
用于插入用于搜索的文本。
<StackPanel>
<TextBox x:Name="textForSearchinInList"/>
<ListBox ItemsSource="{Binding ListOfItems}" x:Name="listOfItems"
SelectedItem="{Binding SelectedUnit, Mode=TwoWay}">
...
</ListBox>
</StackPanel>
List ListOfItems
中包含Bar
类型的对象。我想通过字段name
:
class Bar
{
public string name;
...
}
用户可以在TextBox
中插入文本,相应的项目将从ListBox
中被选中。
基本思想是查找搜索字符串更改,并更新选定的Bar
项。剩下的就交给绑定了。
假设Bar
看起来像这样:
public sealed class Bar
{
public string Name { get; set; }
// ...
}
你可以创建这个视图模型类:
public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
BarItems = new[]
{
new Bar { Name = "Dog" },
new Bar { Name = "Cat" },
new Bar { Name = "Mouse" },
};
}
public string SearchString
{
get { return searchString; }
set
{
if (searchString != value)
{
searchString = value;
SelectedBar = BarItems.FirstOrDefault(_ => !string.IsNullOrEmpty(_.Name) && _.Name.IndexOf(searchString, StringComparison.CurrentCultureIgnoreCase) >= 0);
OnPropertyChanged();
}
}
}
private string searchString;
public Bar SelectedBar
{
get { return selectedBar; }
set
{
if (selectedBar != value)
{
selectedBar = value;
OnPropertyChanged();
}
}
}
private Bar selectedBar;
public IEnumerable<Bar> BarItems { get; }
// INPC implementation is omitted
}
,并这样使用:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1">
<Window.DataContext>
<local:ViewModel />
</Window.DataContext>
<StackPanel>
<TextBox Text="{Binding SearchString, UpdateSourceTrigger=PropertyChanged}"/>
<ListBox ItemsSource="{Binding BarItems}" SelectedItem="{Binding SelectedBar}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type local:Bar}">
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Window>
通过搜索列表并将selectecUnit设置为找到的:
SelectedUnit = ListOfItems.FirstOrDefault(x=>x.name == testForSearchingInList.Text);
可以直接或同步绑定所选项
<ListBox SelectedItem="FoundItem" IsSynchronizedWithCurrentItem="True"
表示ViewModel中研究的结果,并使用c.tor
public YourViewModel()
{
IList<Bar> bars = GetBars().ToList();
_barView = CollectionViewSource.GetDefaultView(bars);
_barView.CurrentChanged += BarSelectionChanged;
和一个委托命令来查找项
FoundItem = ListOfItems.FirstOrDefault( x => x.name // etc..