2015-08-28 69 views
21

我需要編輯一些層次結構,我用TreeViewTextBoxes樹型視圖與文本框在WPF:類型特殊字符

簡短的例子

<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

+0

'Key.Multiply'應該可以正常工作。它在我的解決方案中。 – Kcvin

+0

@NETscape,如果我嘗試在選擇「0級」項目時在文本框中輸入「Key.Multiply」,它不起作用 – ASh

+0

啊,現在我已經選擇了項目,先選擇了它,工作。有趣! – Kcvin

回答

14

終於解決了這個問題Key.Subtract

我在接收Key.Subtract加入處理程序PreviewKeyDownTextBox

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

,爲已處理KeyDown被標記,然後我手動提高TextInput事件如本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 
       }); 
    } 
} 
5

我可以建議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;確實會阻止默認行爲。

+0

謝謝你的建議,'txt.Text + =「 - 」;'不完全是我所需要的(可以選擇要替換的文本)。我不得不尋找另一種解決方法 – ASh