Search code examples
c#wpfxamltreeview

TreeViewItem with TextBox in WPF: type special characters


I need to edit some hierarchical structure and I use TreeView with TextBoxes

Short example

<TreeView>
    <TreeView.Items>
        <TreeViewItem Header="Level 0">
            <!-- Level 1-->
            <TextBox Margin="5"
                     BorderThickness="1" BorderBrush="Black" />
        </TreeViewItem>
    </TreeView.Items>
</TreeView>

When I type in TextBox, +, -, letters and digits work fine, arrows work but when I press -, Level 0 item collapses and when I type *, nothing happens

How should I handle - and * to see them in TextBox as expected?

Edit:

- works if typed as Key.OemMinus but not from numeric keyboard as Key.Subtract

* works if typed as Shift+Key.D8 but not from numeric keyboard as Key.Multiply


Solution

  • finally solved the problem with Key.Subtract

    I added handler to PreviewKeyDown on TextBox

    <TextBox Margin="5" BorderThickness="1" BorderBrush="Black" 
             PreviewKeyDown="TextBoxPreviewKeyDown"
    />
    

    on receiving Key.Subtract, KeyDown is marked as handled and then i manually raise TextInput event as explained in this answer (How can I programmatically generate keypress events in C#? )

    private void TextBoxPreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Subtract)
        {
            e.Handled = true;
    
            var text = "-";
            var target = Keyboard.FocusedElement;
            var routedEvent = TextCompositionManager.TextInputEvent;
    
            target.RaiseEvent(
                new TextCompositionEventArgs
                    (
                         InputManager.Current.PrimaryKeyboardDevice,
                        new TextComposition(InputManager.Current, target, text)
                    )
                    {
                        RoutedEvent = routedEvent
                    });
        }
    }