WPF中ComboBox中的TextChanged事件

前言

最近在做WPF项目,有一个需求是用户在文本框搜索的时候,弹出下拉框预测用户想输入的信息,一开始想用TextBox做,后来觉得写下拉框的UI太麻烦了,于是换了一种思路,改用ComboBox做,只要每次在文本改变时换一下他的ItemsSource即可。

问题

一开始迟迟找不到ComboBox的TextChanged事件,用的是keyUp来做,每次keyUp时获取ComboBox中的文本内容,但是这样会有种种bug,后来用了TextChanged后完美解决。

解决

TextBoxBase.TextChanged即是ComboBox的TextChanged事件。
代码使用方法如下:
界面:

 <ComboBox x:Name="ComboBox_Prescription" Width="150"  DisplayMemberPath="PrescriptionShortCode" SelectedValuePath="Id" FontSize="12"
   IsTextSearchEnabled="False" BorderThickness="0" Focusable="True"
   TextBoxBase.TextChanged="ComboBox_Prescription_TextChanged"
   IsEditable="True">
 </ComboBox>

后台:

 private void ComboBox_Prescription_TextChanged(object sender, RoutedEventArgs e)
 {
     ComboBox_Prescription.IsDropDownOpen = true;
     string input = ComboBox_Prescription.Text;
     if (!string.IsNullOrEmpty(input))
     {
         Prescription pres = new Prescription();
         pres.PrescriptionShortCode = input;
         List<Prescription> pList = presDao.getPrescriptionListByShortCodeFuzzy(pres);
         ComboBox_Prescription.ItemsSource = pList;
     }
     else
     {
         List<Prescription> pList = presDao.getAll();
         ComboBox_Prescription.ItemsSource = pList;
     }
 }

你可能感兴趣的:(wpf)