Search code examples
wpfxamlcomboboxmvvm-lighteventtocommand

How to use an EventToCommand with an editable Combobox to bind TextBoxBase.TextChanged with a command?


I have an editable ComboBox.

<ComboBox IsEditable="True">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <cmd:EventToCommand Command="{Binding CritereChangedCommand, Mode=OneWay}"/>
        </i:EventTrigger>
        <i:EventTrigger EventName="TextBoxBase.TextChanged">
            <cmd:EventToCommand Command="{Binding CritereChangedCommand, Mode=OneWay}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</ComboBox>

I use GalaSoft.MvvmLight.Command.EventToCommand to bind the SelectionChanged event.
I also would like to bind the TextChanged event, but it is a little bit tricky: This event is only accessible by the ComboBox TextBoxBase property, and I can't find the proper way to bind this event.
You can see one of my unsuccessful attempt: SelectionChanged binding works fine, but TextChanged binding does not.

I also tried this syntax:

<ComboBox IsEditable="True">
    <TextBoxBase>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="TextChanged">
                <cmd:EventToCommand Command="{Binding CritereChangedCommand, Mode=OneWay}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </TextBoxBase>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <cmd:EventToCommand Command="{Binding CritereChangedCommand, Mode=OneWay}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</ComboBox>

But this won't even compile. I get an error "Type that can be instantiated expected" on the TextBoxBase tag.

Any idea ?


Solution

  • I have found a way to work around the problem:
    I create an invisible TextBox, bound to the ComboBox, and I bind the command on the TextChanged event of the TextBox. It's not pretty, but it works...

    <ComboBox Name="CbRubrique" IsEditable="True">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="SelectionChanged">
                <cmd:EventToCommand Command="{Binding CritereChangedCommand, Mode=OneWay}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </ComboBox>
    <TextBox Text="{Binding ElementName=CbRubrique, Path=Text, UpdateSourceTrigger=PropertyChanged}" Visibility="Collapsed">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="TextChanged">
                <cmd:EventToCommand Command="{Binding CritereChangedCommand, Mode=OneWay}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </TextBox>