我只是想在按下 Return Shift 時移到新行。
我從以前的帖子中得到了很多:
<TextBox.InputBindings>
<KeyBinding Key="Return" Modifiers="Shift" Command=" " />
</TextBox.InputBindings>
但我找不到任何解釋如何在文本框中完成移動到新行的地方。
我不能使用: AcceptsReturn="True" 因為我想回傳來觸發一個按鈕。
uj5u.com熱心網友回復:
如果您沒有ICommand定義,則可以將UIElement.PreviewKeyUp事件的處理程式附加到TextBox. 否則,您將必須定義一個ICommand實作并將其分配給KeyBinding.Command以便KeyBinding可以實際執行。兩種解決方案最終都會執行相同的邏輯來添加換行符。
然后使用該TextBox.AppendText方法附加換行符,并使用該TextBox.CaretIndex屬性將插入符號移動到新行的末尾。
主視窗.xaml
<Window>
<TextBox PreviewKeyUp="TextBox_PreviewKeyUp" />
</Window>
主視窗.xaml.cs
partial class MainWindow : Window
{
private void TextBox_PreviewKeyUp(object sender, KeyEventArgs e)
{
if (!e.Key.Equals(Key.Enter)
|| !e.KeyboardDevice.Modifiers.HasFlag(ModifierKeys.Shift))
{
return;
}
var textBox = sender as TextBox;
textBox.AppendText(Environment.NewLine);
textBox.CaretIndex = textBox.Text.Length;
}
}
uj5u.com熱心網友回復:
我找到了一種不使用 ICommand 的好方法。
只需將此 PreviewKeyDown 事件添加到 xaml 中的控制元件上:
PreviewKeyDown="MessageText_PreviewKeyDown"
這是背后的 C#:
private void MessageText_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
// Get the textbox
var textbox = sender as TextBox;
// Check if we have pressed enter
if (e.Key == Key.Enter && Keyboard.Modifiers.HasFlag(ModifierKeys.Shift))
{
// Add a new line where cursor is
var index = textbox.CaretIndex;
// Insert a new line
textbox.Text = textbox.Text.Insert(index, Environment.NewLine);
// Shift the caret forward to the newline
textbox.CaretIndex = index Environment.NewLine.Length;
// Mark this key as handled by us
e.Handled = true;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/313982.html
