C# 在WPF中打开控件焦点上的自动完成框
我正在尝试打开控件焦点上的C# 在WPF中打开控件焦点上的自动完成框,c#,wpf,autocomplete,C#,Wpf,Autocomplete,我正在尝试打开控件焦点上的System.Windows.Controls.AutoCompleteBox。事件会触发,但什么也没有发生:/I当我开始输入一些文本时,“自动完成”框工作正常。我做错了什么 AutoCompleteBox box = new AutoCompleteBox(); box.Text = textField.Value ?? ""; box.ItemsSource = textField.Proposals; box.FilterMode = AutoCompleteFi
System.Windows.Controls.AutoCompleteBox
。事件会触发,但什么也没有发生:/I当我开始输入一些文本时,“自动完成”框工作正常。我做错了什么
AutoCompleteBox box = new AutoCompleteBox();
box.Text = textField.Value ?? "";
box.ItemsSource = textField.Proposals;
box.FilterMode = AutoCompleteFilterMode.Contains;
box.GotFocus += (sender, args) =>
{
box.IsDropDownOpen = true;
};
我做了一个快速的变通,好像这个解决方案在我的程序中对我来说是令人满意的
AutoCompleteBox box = new AutoCompleteBox();
box.Text = textField.Value ?? "";
if (textField.Proposals != null)
{
box.ItemsSource = textField.Proposals;
box.FilterMode = AutoCompleteFilterMode.None;
box.GotFocus += (sender, args) =>
{
if (string.IsNullOrEmpty(box.Text))
{
box.Text = " "; // when empty, we put a space in the box to make the dropdown appear
}
box.Dispatcher.BeginInvoke(() => box.IsDropDownOpen = true);
};
box.LostFocus += (sender, args) =>
{
box.Text = box.Text.Trim();
};
box.TextChanged += (sender, args) =>
{
if (!string.IsNullOrWhiteSpace(box.Text) &&
box.FilterMode != AutoCompleteFilterMode.Contains)
{
box.FilterMode = AutoCompleteFilterMode.Contains;
}
if (string.IsNullOrWhiteSpace(box.Text) &&
box.FilterMode != AutoCompleteFilterMode.None)
{
box.FilterMode = AutoCompleteFilterMode.None;
}
};
}
@elgonzo推荐的解决方案非常适合我 XAML: 和代码隐藏:
private void AutoCompleteBox_GotFocus(object sender, System.Windows.RoutedEventArgs e)
{
var _acb = sender as AutoCompleteBox;
if(_acb != null && string.IsNullOrEmpty(_acb.Text))
{
_acb.Dispatcher.BeginInvoke((Action)(() => { _acb.IsDropDownOpen = true; }));
}
}
当没有输入文本且自动完成框获得焦点时,会出现下拉列表。这里对Silverlight没有太多经验,但可能值得尝试
box.Dispatcher.BeginInvoke((操作)(()=>{box.IsDropDownOpen=true;}))
。我怀疑控件内部对焦点事件的处理会妨碍您打开下拉列表。使用Dispatcher队列,可以在焦点事件完全处理后打开下拉列表。另一个原因可能是,如果没有匹配的项,AutoCompleteFilterMode.Contains不允许打开下拉列表。尝试使用AutoCompleteTFilterMode.None,看看会发生什么……两个方案都有帮助,但还有一个问题。当有东西写在盒子里时,一切都能正常工作——当没有东西时,下拉列表根本不会出现:(你的意思是,即使使用了AutoCompleteFilterMode.None,并且AutoCompleteBox的ItemsSource至少包含一个元素(a-ka非空)下拉列表也不会出现吗(即使你在回答自己的问题)?了解其他陷入类似问题的人可能会有所帮助。。。
xmlns:wpftk="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit"
private void AutoCompleteBox_GotFocus(object sender, System.Windows.RoutedEventArgs e)
{
var _acb = sender as AutoCompleteBox;
if(_acb != null && string.IsNullOrEmpty(_acb.Text))
{
_acb.Dispatcher.BeginInvoke((Action)(() => { _acb.IsDropDownOpen = true; }));
}
}