How do I get TextChanged events from an editable ComboBox

PreviewTextInput event gets triggered for every keyboard input in the ComboBox.


<ComboBox IsEditable="True" TextBoxBase.TextChanged="ComboBox_TextChanged" />

...should do it. (Assuming you want something that will fire every time a change is made to the text, rather then when the user has finished entering the text. In which case you'd need another event - maybe a LostFocus event or something?)

Anyway, the reason why the above XAML works is that, when IsEditable is set to true, the ComboBox uses a TextBox for displaying and editing the text. The TextBox's TextChanged event is a bubbling event - meaning it will bubble up through the element tree so we can handle it on the ComboBox itself.

The only 'tricky' bit is that ComboBox doesn't expose a TextChanged event itself but you can still define a handler for it using an attached event (hence the TextBoxBase.TextChanged syntax).

(It's probably worth noting for completeness, that if the ComboBox happened to contain more than one TextBox then the handler would be called whenever any of them had their text changed.)


Add --->> TextBoxBase.TextChanged="ComboBox_TextChanged"


Based on the approach above I had a look into the (XAML) generated code.

<ComboBox x:Name="myComboBox" IsEditable="True"/>

Add the following code to initialization:

myComboBox.AddHandler(System.Windows.Controls.Primitives.TextBoxBase.TextChangedEvent, 
                      new System.Windows.Controls.TextChangedEventHandler(ComboBox_TextChanged));

This works fine for me, because I needed a reusable ComboBox (SQL-Server dropdown list) which encapsulates all behaviour.

Tags:

Wpf