Basically what I have is a wpf combo box with both isTextSearchEnable and isEditable, enabled. I want to allow use to key in what they want to find and filter the combo box items to show relatable items only.
If the user keys in MP-1, it should only show items that contains with those text and not show unrelated items. So far, the code works for the 2nd character but not the first. Any ideas or what am I doing wrong here?
The code that I have so far,
public class FilterViewModel
{
public IEnumerable<string> DataSource { get; set; }
public FilterViewModel()
{
DataSource = new[] { "MP-10001", "MP-10002", "MP-10003", "MP-10004", "XD-20001", "XD-20002", "XD-20003" };
}
}
public MainWindow()
{
InitializeComponent();
FilterViewModel vm = new FilterViewModel();
this.DataContext = vm;
}
private void FilteredCmb_KeyUp(object sender, KeyEventArgs e)
{
CollectionView cv = (CollectionView)CollectionViewSource.GetDefaultView(cmbBox.ItemsSource);
cv.Filter = ((o) =>
{
if (String.IsNullOrEmpty(cmbBox.Text)) return true;
else
{
if (((string)o).Contains(cmbBox.Text)) return true;
else return false;
}
});
cv.Refresh();
}
<Grid>
<ComboBox x:Name="cmbBox" HorizontalAlignment="Left" Margin="78,36,0,0" VerticalAlignment="Top" Width="362" IsEditable="True" IsTextSearchEnabled="True" Height="47" KeyUp="FilteredCmb_KeyUp" StaysOpenOnEdit="True" IsDropDownOpen="True" ItemsSource="{Binding DataSource}"/>
</Grid>