是否可以在WPF应用程序中以某种方式向文本框添加自动完成建议?就像我将建议绑定到DataTable或字符串列表的位置一样?文本框可以吗?
<TextBox Text="{Binding InputText, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
VerticalContentAlignment="Center" >
<TextBox.InputBindings>
<KeyBinding Command="{Binding EnterKeyPressedCommand}" Key="Return" />
</TextBox.InputBindings>
</TextBox>
如果您在寻找起点时遇到困难,实际上涉及几个步骤,并且可能有几种方法可以做到这一点。
在我的头顶上方,您可以创建一个隐藏的内容ListBox
,TextBox
其中包含您的建议(请确保ListBox
内容的大小)。随着文本的更改,您可以使用一个简单的TestChanged
事件。
XAML:
<TextBox x:Name="someTextbox"
TextChanged="someTextbox_TextChanged"
</TextBox>
背后的代码:
private void someTextbox_TextChanged(object sender, TextChangedEventArgs e)
{
// Call method to check for possible suggestions.
// Display Listbox with suggested items.
}
然后,单击中的项目Listbox
将更新文本。
注意:当用户从菜单中选择建议时,您将需要某种方式来防止事件运行逻辑ListBox
现在用于MVVM:
private string _SomeTextbox = "";
public string SomeTextbox
{
get { return _SomeTextbox; }
set
{
_SomeTextbox = value;
OnPropertyChanged(new PropertyChangedEventArgs("SomeTextbox"));
// Call method to check for possible suggestions.
// Display Listbox with suggested items.
}
}
使用MVVM,您可以ListBox
相对轻松地绑定可见性和内容,然后根据需要进行显示。
执行此操作的另一种方法是将TextBox
默认设置编辑为内置ListBox
。不过,这条路要复杂得多。
希望这可以帮助您入门。