I'm trying to create an attached behavior to add an auto-complete list to the standard TextBox
control. My goal is that every time the TextChanged
event is raised, my AutoCompleteBehavior
class creates a popup and fills it with potential auto-complete results.
To get these results, my AutoCompleteBehavior
declares the following event:
Public Shared ReadOnly AutoCompleteListRequestedEvent As RoutedEvent =
EventManager.RegisterRoutedEvent("AutoCompleteListRequested",
RoutingStrategy.Bubble,
GetType(AutoCompleteListRequestedEventHandler), GetType(AutoCompleteBehavior))
The above is meant to be an attached event, used like this:
<TextBox lib:AutoCompleteBehavior.AutoCompleteListRequested="EventHandlerHere"/>
The idea is that when TextChanged
is raised, AutoCompleteBehavior.AutoCompleteListRequested
is also raised, which asks the implementing program to supply a list of suggestions for the current input.
For this to work, I have to hook in to the TextBox.TextChanged
event as soon as my attached event is attached to said TextBox
. Per Microsoft I should be able to declare a sub Add*Handler
and Remove*Handler
where the "*" is the name of the attached event, and these would be called whenever the attached event is added or removed from an element.
So right below the event declaration I have:
Public Shared Sub AddAutoCompleteListRequestedHandler(TB As TextBox, handler As AutoCompleteListRequestedEventHandler)
'Code to hook into TextBox.TextChanged
End Sub
Public Shared Sub RemoveAutoCompleteListRequestedHandler(TB As TextBox, handler As AutoCompleteListRequestedEventHandler)
'Code to unhook fromTextBox.TextChanged
End Sub
My problem is AddAutoCompleteListRequestedHandler
is never called. If I call TextBox.RaiseEvent
to raise AutoCompleteListRequested
, the event handler defined in XAML does get called (so the event is attached), but it seems my AddAutoCompleteListRequestedHandler
is completely skipped.
As a final note, I found this question here which seems to be describing the same problem (my code is also in a dll just like his), but it's two years old and was never answered.
The XAML processor won't call your static methods when hooking up the event handler.
If you want to do something when the TextBox
raises the TextChanged
event, you would probably be better off implementing an attached behaviour and hook up to the TextChanged
event in the PropertyChangedCallback
or in the OnAttached()
method depending on which kind of behaviour you create.
Please refer to my answer here for more information about attached behaviours.