[C#][WPF]Combobox根據輸入內容篩選下拉式選單

  • 10520
  • 0

若需要讓使用者輸入文字後,可以顯示出接近的選項,供使用者選擇,該如何實作?

首先拉一個Combobox。

設定Combobox屬性
直接在Xamal中設定Combobox的屬性,並加入一個KeyUp事件。

屬性說明如下:
1.「ItemsSource」屬性:用於設定Combobox下拉選單的資料來源。
2.「IsEditable」屬性:設定是否可以輸入文字,在此設為True
3.「IsTextSearchEnabled」屬性:設定是否可以自動完成輸入,
若使用者輸入一半則可以自動輸入後半段文字,在此不需要此功能,
所以設為False
4.「IsDropDownOpen」屬性:設定是否顯示下拉式選單,
一開始先不用顯示下拉式選單,所以設為False
5.「StaysOpenOnEdit」屬性:設定在使用者輸入文字時,
是否保持開啟下拉式選單,在此設為True

資料繫結
在CodeBehind中,撰寫資料繫結程式:

public MainWindow()
{
   InitializeComponent();

   List<string> itemNames = GetData();//準備資料
   comboBox.ItemsSource = itemNames;  //資料繫結
}


private List<string> GetData()
{
   List<string> list = new List<string>();
   list.Add("1A2356");
   list.Add("JP2346");
   list.Add("RV0970");
   list.Add("2624HP");
   return list;
}

KeyUp事件處理函式
為了反映使用者所輸入的文字,必須在此撰寫相關程式碼:

private void comboBox_KeyUp(object sender, KeyEventArgs e)
{
   ComboBox cmb = (ComboBox)sender;
   CollectionView itemsViewOriginal = (CollectionView)CollectionViewSource.GetDefaultView(cmb.ItemsSource);
			
   itemsViewOriginal.Filter = ((o) =>
   {
      if (string.IsNullOrEmpty(cmb.Text)) return false;
      else
      {
         if (((string)o).StartsWith(cmb.Text)) return true;
         else return false;
      }
   });

   cmb.IsDropDownOpen = true;
   itemsViewOriginal.Refresh();
			
}

考慮大量的資料來源
大量的資料來源會使程式反映變慢,可使用「VirtualizingStackPanel」加以改善。
在Xamal中加入VirtualizingStackPanel程式碼如下:

<ComboBox x:Name="comboBox" HorizontalAlignment="Left" Height="36" 
          Margin="10,10,0,0" VerticalAlignment="Top" Width="356"
          ItemsSource="{Binding}" IsEditable="True" IsTextSearchEnabled="false" 
          IsDropDownOpen="false" StaysOpenOnEdit="True"
          KeyUp="comboBox_KeyUp"  >

   <ComboBox.ItemsPanel>
      <ItemsPanelTemplate>
          <VirtualizingStackPanel />
      </ItemsPanelTemplate>
   </ComboBox.ItemsPanel>

</ComboBox>