在控件焦点上打开WPF中的AutoCompleteBox

时间:2013-11-21 12:35:59

标签: c# wpf autocomplete

我正试图在控制焦点上打开System.Windows.Controls.AutoCompleteBox。事件触发但没有任何反应:/当我开始输入一些文本时,自动完成框工作正常。我究竟做错了什么?

AutoCompleteBox box = new AutoCompleteBox();
box.Text = textField.Value ?? "";
box.ItemsSource = textField.Proposals;
box.FilterMode = AutoCompleteFilterMode.Contains;
box.GotFocus += (sender, args) =>
    {
        box.IsDropDownOpen = true;
    };

2 个答案:

答案 0 :(得分:6)

我做了一个快速的解决方法,好像这个解决方案在我的程序中对我来说很满意。

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;
            }
        };
}

答案 1 :(得分:0)

来自@elgonzo的推荐解决方案非常适合我。

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"

和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; }));
    }
}

当尚未输入文本且AutoCompleteBox获得焦点时,将显示下拉列表。