TextCompositionEvent and PreviewTextInput

Viewed 200

I'm sending programmatically some text via InputManager to TextBox, but it does not fire PreviewTextInput before changing Text.

WPF application with on screen keyboard. In some cases (inputing currency etc.) text need to be validated before introducing to TextBox.

        var target = TKeyboard.FocusedElement;
        var eventArgs = new TextCompositionEventArgs(
            Keyboard.PrimaryDevice,
            new TextComposition(InputManager.Current, target, text))
        {
            RoutedEvent = UIElement.TextInputEvent
        };
        InputManager.Current.ProcessInput(eventArgs);

I need to add text programmatically and be able to validate it before inputing into TextBox. Maybe it's not possible this way and I need different approach?

1 Answers

If Keyboard.FocusedElement returns the right control, then set the Source for the eventArgs to the target and use UIElement.PreviewTextInputEvent in TextComposition object. .

var target = Keyboard.FocusedElement;
var eventArgs = new TextCompositionEventArgs(
    Keyboard.PrimaryDevice,
    new TextComposition(InputManager.Current, target, text))
{
    RoutedEvent = UIElement.PreviewTextInputEvent //   <==Use another event
};
eventArgs.Source = target; //   <==Set the Source
InputManager.Current.ProcessInput(eventArgs);
Related