The basic idea is to look for search string changes, and update selected Bar
item. Binding will do the rest.
Assuming, that Bar
looks like this:
public sealed class Bar
{
public string Name { get; set; }
// ...
}
you can create this view model class:
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
}
and use it this way:
<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>