AcceptsReturn="False" for AvalonEdit

本文关键字:quot AvalonEdit for False AcceptsReturn | 更新日期: 2023-09-27 18:31:39

我需要一個單行的AvalonEdit控件(等效於AcceptsReturn="False"的TextBox)。

AvalonEdit 似乎没有此属性。

如何为 AvalonEdit 执行此操作?

AcceptsReturn="False" for AvalonEdit

您可以尝试处理 PreviewKeyDown 事件,如果密钥为 Return,则将e.Handled设置为 true。

此外,我猜您想防止将换行符粘贴到文本区域中。这必须通过以下操作来完成:

void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    // Find the Paste command of the avalon edit
    foreach (var commandBinding in textEditor.TextArea.CommandBindings.Cast<CommandBinding>())
    {
        if (commandBinding.Command == ApplicationCommands.Paste)
        {
            // Add a custom PreviewCanExecute handler so we can filter out newlines
            commandBinding.PreviewCanExecute += new CanExecuteRoutedEventHandler(pasteCommandBinding_PreviewCanExecute);
            break;
        }
    }
}
void pasteCommandBinding_PreviewCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    // Get clipboard data and stuff
    var dataObject = Clipboard.GetDataObject();
    var text = (string)dataObject.GetData(DataFormats.UnicodeText);
    // normalize newlines so we definitely get all the newlines
    text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
    // if the text contains newlines - replace them and paste again :)
    if (text.Contains(Environment.NewLine))
    {
        e.CanExecute = false;
        e.Handled = true;
        text = text.Replace(Environment.NewLine, " ");
        Clipboard.SetText(text);
        textEditor.Paste();
    }
}

这是我的Editor.TextArea.PreviewKeyDown处理程序:

    private void TabToOkayBtn(object sender, KeyEventArgs args)
    {
        if (args.Key == Key.Tab)
        {
            args.Handled = true;
            Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(() => // input priority is always needed when changing focus
                _editor.TextArea.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next))));
        }
    }

您还可以检查转到"上一个"的移位状态,并使用三元运算符选择方向:

var shiftPressed = (args.KeyboardDevice.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift;