views:

249

answers:

1

I have the following code. The window has a textbox and a checkbox. If I have focus on the anything other than checkbox and type something like 123-456 then for each character PreviewKeyDown and PreviewTextInput are firing.

But if I have the focus to checkbox and then type 123-456 then the PreviewKeyDown is fired for all the characters whereas PreviewTextInput fires only for 123456 and doesn't fire for '-'. The hyphen is being handled by the checkbox and not getting passed to PreviewTextInput. Is there a way to get the hyphen to PreviewTextInput?

 public Window1()
        {
            InitializeComponent();

            TextCompositionManager.AddTextInputHandler(this, new TextCompositionEventHandler(Window_PreviewTextInput));       
        }

private void Window_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {

        }

private void Window_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
}
A: 

I found a way to do this but I want to know from experts if there is a problem with my solution or a better way to do this.

In the KeyDown event of the window I am marking the Handled to false. The checkbox sets the Handled to true in the KeyDown and in the Window's KeyDown I am setting it to false and this will call the PreviewTextInput as the event still needs to be handled.

public Window1()
        {
            InitializeComponent();
            TextCompositionManager.AddPreviewTextInputStartHandler(this, new TextCompositionEventHandler(Window_PreviewTextInput));
            this.AddHandler(Window.KeyDownEvent, new System.Windows.Input.KeyEventHandler(Window_KeyDown), true);
        }

private void Window_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
        }

private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            e.Handled = false;
        }
Ragha J
One obvious thing I would see is a performance issue as the events have to travel more the tree now for some controls.
Ragha J