Hi,
May be below sample code can help, just copy paste the code and run.
View:
Xaml:
<window x:class="FilterableCombobox.MainWindow" xmlns:x="#unknown">
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<window.resources>
<style targettype="{x:Type ComboBox}">
<style.setters>
<setter property="ItemTemplate">
<setter.value>
<datatemplate>
<stackpanel orientation="Horizontal">
<label content="{Binding FirstCol}"></label>
<label content="{Binding SecondCol}"></label>
</stackpanel>
</datatemplate>
</setter.value>
</setter>
</style.setters>
</style>
</window.resources>
<grid>
<combobox itemssource="{Binding FilterItems}" iseditable="True" text="{Binding ComboText}"></combobox>
</grid>
</window>
C#:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
}
}
View Model:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
namespace FilterableCombobox
{
public class MyComboItem
{
public string FirstCol { get; set; }
public string SecondCol { get; set; }
}
internal class MainWindowViewModel : INotifyPropertyChanged
{
private ObservableCollection<mycomboitem> _items;
private ObservableCollection<mycomboitem> _filterItems;
private string _comboText;
public MainWindowViewModel()
{
_items = new ObservableCollection<mycomboitem>();
_items.Add(new MyComboItem() { FirstCol = "1", SecondCol = "2" });
_items.Add(new MyComboItem() { FirstCol = "A", SecondCol = "B" });
_items.Add(new MyComboItem() { FirstCol = "3", SecondCol = "4" });
_items.Add(new MyComboItem() { FirstCol = "C", SecondCol = "D" });
FilterItems = _items;
}
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<mycomboitem> FilterItems
{
get { return _filterItems; }
set
{
_filterItems = value;
InvokePropertyChanged("FilterItems");
}
}
public string ComboText
{
get { return _comboText; }
set
{
_comboText = value;
InvokePropertyChanged("ComboText");
if(string.IsNullOrWhiteSpace(_comboText))
{
FilterItems = _items;
}
else
{
FilterItems=new ObservableCollection<mycomboitem>(
from i in _items where i.FirstCol.Contains(value) || i.SecondCol.Contains(value)
select i
);
}
}
}
protected void InvokePropertyChanged(string prop)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(prop));
}
}
}
enjoy!!