Lexu
Lexu

Reputation: 579

WPF ComboBox autocomplete from items

I have a ComboBox where I load in every hour and minute constellation possible. This gives many items and to still keep this user friendly I want an autocomplete. But the thing is when I turn IsEditable="true" a user can also enter any value.

<ComboBox x:Name="cmbStartZeit" IsTextSearchEnabled="True" />

I add the items in two for loops

for(int i = 00; i <= 24; i++)
{
    for(int j = 00; j <= 59; j++)
    {
       cmbStartZeit.Items.Add(i.ToString("00") + ":" + j.ToString("00"));
    }
}

How can I turn the autocomplete feature on without allowing the user to add custom values ?

Upvotes: 2

Views: 4681

Answers (1)

bars222
bars222

Reputation: 1660

You can check if combobox items contains entered text in TextChanged event. So xaml code looks like this.

<ComboBox Name="cbTest" IsTextSearchEnabled="True" IsEditable="True"
          TextBoxBase.TextChanged="cbTest_TextChanged" />

And the code behinde should look like this. This code prevents user input, that not in combobox items.

string _prevText = string.Empty;

private void cbTest_TextChanged( object sender, TextChangedEventArgs e )
{
    foreach ( var item in cbTest.Items )
    {
        if ( item.ToString().StartsWith( cbTest.Text ) )
        {
            _prevText = cbTest.Text;
            return;
        }
    }
    cbTest.Text = _prevText;
}

Upvotes: 3

Related Questions