I'm creating a Custom Control
inherit TextBox
, however, as PreviewTextInput
and TextInput
is not handled in TextBox
by default, I wanted implement a PreviewTextInputLinked
and TextInputLinked
for my control, just for developer can add or remove these two events using +=
and -=
I have created a TextCompositionEventHandler
called PreviewTextInputLinked
TextInputLinked
public event TextCompositionEventHandler /*PreviewTextInputLinked*/ TextInputLinked = delegate { };
public MyTextBox()
{
this.AddHandler(TextBox.PreviewTextInputEvent, /*PreviewTextInputLinked */TextInputLinked, true);
}
In the program XAML
/*<UControls:MyTextBox VerticalAlignment="Top" AcceptLetters="9" Mask=""
Width="122"
PreviewTextInputLinked="MyTextBox_PreviewTextInputLinked"/>*/
<UControls:MyTextBox VerticalAlignment="Top" Width="122"
TextInputLinked="MyTextBox_TextInputLinked"/>
Code behind
private void /*MyTextBox_PreviewTextInputLinked*/ MyTextBox_TextInputLinked(object sender,
TextCompositionEventArgs e)
{
MessageBox.Show("test");
}
But it is not doing anything, maybe I'm doing wrong, but I don't know what more can I do
Where is the problem?
PreviewTextInput
will work since this is a tunnelling event
whereas TextInput
is a bubble event
. In case it is handled while routing up, it won't bubble up to visual tree that's why hooking to PreviewTextInput
works and TextInput
doesn't because it might be handled somewhere en-route of bubbling.
AddHandler
is a way to achieve that which you are using. Notice its third bool parameter which corresponds to handledEventsToo
ie you still want handler to be called even it is handled below down Visual Tree by some element.
Now issue in your code is you pass an empty delegate
to it which will get execute just like you want but you manually need to call other delegates (hooked via XAML to that event) which can be achieved like this -
public event TextCompositionEventHandler TextInputLinked = (sender, args) =>
{
MyTextBox textBox = (MyTextBox)sender;
if (textBox.TextInputLinked != null)
{
foreach (var handler in textBox.TextInputLinked.GetInvocationList())
{
if (handler.Target != null) <-- Check to avoid Stack overflow exception
{
handler.DynamicInvoke(sender, args);
}
}
}
};
public MyTextBox()
{
this.AddHandler(TextBox.TextInputEvent, TextInputLinked, true);
}
Now other handlers will be called as you desired.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.