TreeViewItem with TextBox in WPF: type special characters

I can suggest a keydown event for the textboxes that you have.

<TextBox Margin="5" KeyDown="TextBox_KeyDown"
                     BorderThickness="1" BorderBrush="Black" />


 private void TextBox_KeyDown(object sender, KeyEventArgs e)
 {
    TextBox txt = sender as TextBox;
    if(e.Key == Key.Subtract)
    {
        txt.Text += "-";
        txt.SelectionStart = txt.Text.Length;
        txt.SelectionLength = 0;
        e.Handled = true;
    }
    else if (e.Key == Key.Multiply)
    {
        txt.Text += "*";
        txt.SelectionStart = txt.Text.Length;
        txt.SelectionLength = 0;
        e.Handled = true;
    }
}

It's not a good solution but it works. If you have any other "problem" keys, you can add an if to the event.

SelectionStart and SelectionLength are for positioning cursor at the end of textbox. And e.Handled = true; does prevent the default behaviour.


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
                });
    }
}