我有一个如下所示的 Nationality ComboBox,并且想要制作它以便用户可以键入字母来缩小选择范围。我可以通过在 NationalityComboBox_KeyDown 方法中添加逻辑来解决这个问题。
这是将 AutoSuggest 构建到 ComboBox 中的最佳方式,还是有内置方式来做同样的事情?
XAML:
<ComboBox x:Class="TestComboSuggest343.NationalityComboBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Value}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
代码隐藏:
public partial class NationalityComboBox : ComboBox
{
public NationalityComboBox()
{
InitializeComponent();
Items.Add(new KeyValuePair<string, string>(null, "Please choose..."));
Items.Add(new KeyValuePair<string, string>(null, "American"));
Items.Add(new KeyValuePair<string, string>(null, "Australian"));
Items.Add(new KeyValuePair<string, string>(null, "Belgian"));
Items.Add(new KeyValuePair<string, string>(null, "French"));
Items.Add(new KeyValuePair<string, string>(null, "German"));
Items.Add(new KeyValuePair<string, string>(null, "Georgian"));
SelectedIndex = 0;
KeyDown += new KeyEventHandler(NationalityComboBox_KeyDown);
}
void NationalityComboBox_KeyDown(object sender, KeyEventArgs e)
{
SelectedIndex = 4; // can create logic here to handle key presses, e.g. "G", "E", "O"....
}
}