WPF TextBox RaiseEvent

4.3k views Asked by At

I have some validation code that uses masking and the PreviewTextInput and PreviewKeyDown events on a textbox. When I change the value in the textbox manually the validation works perfectly. When I set the values programatically the valdation doesn't start until I click in the box and delete a character and re-add it, manually firing one or both of the above events.

Is there a way to fire either of those events manually so that the validation will work?

I've tried stuff like:

this.TextBox.RaiseEvent(this.TextBox.PreviewTextInput);

But nothing seems to work. I can't get the types to match either. Any ideas are welcome.

The masking-based validation code I'm using can be seen here: How to define TextBox input restrictions?

3

There are 3 answers

1
Trevor Elliott On

You can use the following code to fake text input to a TextBox.

TextCompositionEventArgs args = new TextCompositionEventArgs(
    InputManager.Current.PrimaryKeyboardDevice,
    new TextComposition(InputManager.Current, txtBox, "Test text")
);
args.RoutedEvent = TextCompositionManager.PreviewTextInputEvent;

txtBox.RaiseEvent(args);

args = new TextCompositionEventArgs(
    InputManager.Current.PrimaryKeyboardDevice,
    new TextComposition(InputManager.Current, txtBox, "Test text")
);
args.RoutedEvent = TextCompositionManager.TextInputEvent;

txtBox.RaiseEvent(args);
0
Axel Samyn On

To complete Trevor Elliott's answer, I had to reuse the same TextCompositionEventArgs reference to make it work :

    TextCompositionEventArgs eventArgs =
      new TextCompositionEventArgs(
        InputManager
          .Current
          .PrimaryKeyboardDevice,
        new TextComposition(
          InputManager.Current, 
          target, 
          ((char) KeyInterop.VirtualKeyFromKey(KBB.Key)).ToString()));

    eventArgs.RoutedEvent = TextCompositionManager.PreviewTextInputStartEvent;
    target.RaiseEvent(eventArgs);

    eventArgs.RoutedEvent = TextCompositionManager.TextInputStartEvent;
    target.RaiseEvent(eventArgs);

    eventArgs.RoutedEvent = TextCompositionManager.PreviewTextInputEvent;
    target.RaiseEvent(eventArgs);

    eventArgs.RoutedEvent = TextCompositionManager.TextInputEvent;
    target.RaiseEvent(eventArgs);

Hope this helps

0
Stephen Avery On

Or you could just select the text in the textbox after you enter the text via code eg t.Select().

In this way once the user moves focus off the text box, validation will fire.