Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,769 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
How to filter listbox in WPF
Refer below link for filter using ICollectionView and CollectionViewSource.
Auto-complete-quick-search-WPF-ListBox
Below very sample filtering, added data in XAML code only, you can bind listbox as per your need.
C# Code:
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
namespace WpfListboxSearch
{
public partial class MainWindow : Window
{
List<string> Namelist = new List<string>();
public MainWindow()
{
InitializeComponent();
foreach (ListBoxItem lbi in lbNameList.Items)
{
Namelist.Add(lbi.Content.ToString());
}
}
private void txtNameSearch_TextChanged(object sender, TextChangedEventArgs e)
{
if (!string.IsNullOrWhiteSpace(txtNameSearch.Text))
{
lbNameList.Items.Clear();
foreach (string name in Namelist)
{
if (name.ToLower().StartsWith(txtNameSearch.Text.Trim().ToLower()))
{
lbNameList.Items.Add(name);
}
}
}
else if (string.IsNullOrWhiteSpace(txtNameSearch.Text))
{
lbNameList.Items.Clear();
foreach (string name in Namelist)
{
lbNameList.Items.Add(name);
}
}
}
}
}
XAML Code:
<Window x:Class="WpfListboxSearch.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfListboxSearch"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<TextBox Height="23" HorizontalAlignment="Left" Margin="82,11,0,0" Name="txtNameSearch" VerticalAlignment="Top" Width="120" TextChanged="txtNameSearch_TextChanged"/>
<ListBox Height="100" HorizontalAlignment="Left" Margin="86,51,0,0" Name="lbNameList" VerticalAlignment="Top" Width="600" >
<ListBoxItem>David</ListBoxItem>
<ListBoxItem>Rock</ListBoxItem>
<ListBoxItem>Shaan</ListBoxItem>
</ListBox>
</Grid>
</Window>