Nickon
Nickon

Reputation: 10146

Open AutoCompleteBox in WPF on control focus

I'm trying to open System.Windows.Controls.AutoCompleteBox on control focus. 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;
    };

Upvotes: 3

Views: 3021

Answers (2)

dontbyteme
dontbyteme

Reputation: 1261

The recommended solution from @elgonzo worked perfectly for me.

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.

Upvotes: 1

Nickon
Nickon

Reputation: 10146

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

Upvotes: 6

Related Questions