簡體   English   中英

在WPF中使用TextBox的TreeViewItem:鍵入特殊字符

[英]TreeViewItem with TextBox in WPF: type special characters

我需要編輯一些層次結構,我使用TreeViewTextBoxes

簡短的例子

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

當我輸入TextBox+- ,字母和數字工作正常時,箭頭可以正常工作但是當我按-Level 0項目崩潰,當我輸入* ,沒有任何反應

我應該如何處理-*TextBox按預期看到它們?

編輯:

-如果鍵入Key.OemMinus但不能從數字鍵盤鍵入Key.Subtract

*如果鍵入Shift + Key.D8但不能從數字鍵盤Key.Multiply

最后用Key.Subtract解決了這個問題

我在TextBox上為PreviewKeyDown添加了處理程序

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

在接收Key.SubtractKeyDown被標記為已處理,然后我手動提升TextInput事件,如本答案中所述如何在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
                });
    }
}

我可以為你擁有的文本框建議一個keydown事件。

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

這不是一個好的解決方案,但它的工作原理。 如果您有任何其他“問題”鍵,則可以向事件添加if。

SelectionStartSelectionLength用於將光標定位在文本框的末尾。 並且e.Handled = true; 確實可以防止默認行為。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM