在WPF中,要实现在ComboBox中的任何地方自动完成文本,可以使用AutoCompleteBox控件。AutoCompleteBox是一个WPF控件,可以在ComboBox中实现自动完成功能。以下是如何在WPF中使用AutoCompleteBox的步骤:
Install-Package WPFToolkit
xmlns:toolkit="http://schemas.xceed.com/wpf/xaml/toolkit"
<toolkit:AutoCompleteBox ItemsSource="{Binding DataList}" SelectedItem="{Binding SelectedData}" />
其中,DataList是数据源列表,SelectedData是选中的数据项。
public class MainViewModel : INotifyPropertyChanged
{
private List<string> _dataList;
public List<string> DataList
{
get { return _dataList; }
set
{
_dataList = value;
OnPropertyChanged("DataList");
}
}
private string _selectedData;
public string SelectedData
{
get { return _selectedData; }
set
{
_selectedData = value;
OnPropertyChanged("SelectedData");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public MainViewModel()
{
DataList = new List<string> { "Apple", "Banana", "Cherry", "Dog", "Elephant", "Fish", "Giraffe", "Horse", "Igloo", "Jacket", "Kangaroo", "Lemon", "Mango", "Nest", "Orange", "Penguin", "Queen", "Rabbit", "Snake", "Turtle", "Umbrella", "Violin", "Watermelon", "Xylophone", "Yak", "Zebra" };
SelectedData = DataList.FirstOrDefault();
}
这样,在WPF中的任何地方自动完成ComboBox的文本就实现了。
领取专属 10元无门槛券
手把手带您无忧上云