[英]Open AutoCompleteBox in WPF on control focus
I'm trying to open System.Windows.Controls.AutoCompleteBox
on control focus. 我正在尝试在控件焦点上打开System.Windows.Controls.AutoCompleteBox
。 The event triggers but nothing happens:/ When I start entering some text, the autocomplete box works fine. 事件触发但没有任何反应:/当我开始输入一些文本时,自动完成框工作正常。 What am I doing wrong? 我究竟做错了什么?
AutoCompleteBox box = new AutoCompleteBox();
box.Text = textField.Value ?? "";
box.ItemsSource = textField.Proposals;
box.FilterMode = AutoCompleteFilterMode.Contains;
box.GotFocus += (sender, args) =>
{
box.IsDropDownOpen = true;
};
I did a quick workaround as if this solution is satisfying for me in my program. 我做了一个快速的解决方法,好像这个解决方案在我的程序中对我来说很满意。
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;
}
};
}
The recommended solution from @elgonzo worked perfectly for me. 来自@elgonzo的推荐解决方案非常适合我。
XAML: XAML:
<wpftk:AutoCompleteBox FilterMode="Contains"
ItemsSource="{Binding List}"
MinimumPrefixLength="0"
Text="{Binding Text}"
GotFocus="AutoCompleteBox_GotFocus"/>
with namespace 与命名空间
xmlns:wpftk="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit"
and Code-Behind: 和代码隐藏:
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; }));
}
}
The dropdown appears when there is no text entered yet and the AutoCompleteBox got focus. 当尚未输入文本且AutoCompleteBox获得焦点时,将显示下拉列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.