c# - TreeViewItem con TextBox en WPF: escriba caracteres especiales
(2)
Finalmente resolví el problema con Key.Subtract
PreviewKeyDown el controlador a PreviewKeyDown en TextBox
<TextBox Margin="5" BorderThickness="1" BorderBrush="Black"
PreviewKeyDown="TextBoxPreviewKeyDown"
/>
al recibir Key.Subtract , KeyDown se marca como manejado y luego levanto manualmente el evento TextInput como se explica en esta answer ( ¿Cómo puedo generar eventos de pulsación de tecla en 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
});
}
}
Necesito editar alguna estructura jerárquica y uso TreeView con TextBoxes
Breve ejemplo
<TreeView>
<TreeView.Items>
<TreeViewItem Header="Level 0">
<!-- Level 1-->
<TextBox Margin="5"
BorderThickness="1" BorderBrush="Black" />
</TreeViewItem>
</TreeView.Items>
</TreeView>
Cuando TextBox , + , - , las letras y los dígitos funcionan bien, las flechas funcionan pero cuando presiono - , el elemento del Level 0 se colapsa y cuando escribo * , no ocurre nada
¿Cómo debo manejar - y * para verlos en TextBox como se esperaba?
Editar:
- Funciona si se escribe como Key.OemMinus pero no desde el teclado numérico como Key.Subtract
* funciona si se escribe como Shift + Key.D8 pero no desde el teclado numérico como Key.Multiply
Puedo sugerir un evento keydown para los cuadros de texto que tiene.
<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;
}
}
No es una buena solución pero funciona. Si tiene otras claves de "problema", puede agregar un if al evento.
SelectionStart y SelectionLength son para colocar el cursor al final del cuadro de texto. Y e.Handled = true; evita el comportamiento por defecto.