Hodaya Shalom
Hodaya Shalom

Reputation: 4417

Auto Suggest ComboBox - MVVM

When I add to combobox the property IsEditable="True" it automatically receive the "Auto Complete" behavior.

Is there a way to add to this combobox the "Auto Suggest" behavior?

I mean, when writing in the combobox opens a list of options with the above caption.

(If possible = without destroying the MVVM)

Upvotes: 2

Views: 4075

Answers (1)

pushpraj
pushpraj

Reputation: 13669

Here you go

I tried to add the auto suggest kind of behavior using standard combobox and animation

<ComboBox IsEditable="True">
    <ComboBoxItem>Orange</ComboBoxItem>
    <ComboBoxItem>Apple</ComboBoxItem>
    <ComboBoxItem>Banana</ComboBoxItem>
    <ComboBoxItem>Cherry</ComboBoxItem>
    <ComboBox.Triggers>
        <EventTrigger RoutedEvent="TextBoxBase.TextChanged">
            <BeginStoryboard>
                <Storyboard>
                    <BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="IsDropDownOpen">
                        <DiscreteBooleanKeyFrame Value="True" KeyTime="0:0:0"/>
                    </BooleanAnimationUsingKeyFrames>
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </ComboBox.Triggers>
</ComboBox>

Give this a try and let me know if this is what you are looking for, more sophisticated behavior might need some extra efforts

Add suggestion filter for combo Items

xaml

<ComboBox IsEditable="True"
            ItemsSource="{Binding ComboItems}"
            Text="{Binding ComboText,Mode=OneWayToSource}">
    <ComboBox.Triggers>
        <EventTrigger RoutedEvent="TextBoxBase.TextChanged">
            <BeginStoryboard>
                <Storyboard>
                    <BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="IsDropDownOpen">
                        <DiscreteBooleanKeyFrame Value="True"
                                                    KeyTime="0:0:0" />
                    </BooleanAnimationUsingKeyFrames>
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </ComboBox.Triggers>
</ComboBox>

view model

public ICollectionView ComboItems{ get; set; }

public string ComboText
{
    get
    {
        throw new NotImplementedException();
    }
    set
    {
        ComboItems.Filter = item => item.ToString().ToLower().Contains(value.ToLower());
    }
}

you may need to filter based on your items types, above is for string values

to init the ComboItems

var myItems = new[] { "Apple", "Orange", "Cherry", "Banana" };
ComboItems = CollectionViewSource.GetDefaultView(myItems);

replace my items with your collection

Upvotes: 4

Related Questions