【问题标题】:AcceptsReturn="False" for AvalonEditAcceptsReturn="False" 用于 AvalonEdit
【发布时间】:2012-04-20 01:03:41
【问题描述】:

我需要一个单行 AvalonEdit 控件(相当于带有 AcceptsReturn="False" 的 TextBox)。

AvalonEdit 似乎没有这个属性。

如何为 AvalonEdit 执行此操作?

【问题讨论】:

    标签: c# xaml avalonedit


    【解决方案1】:

    如果 Key 为 Return,您可以尝试处理 PreviewKeyDown 事件并将 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();
        }
    }
    

    【讨论】:

      【解决方案2】:

      这是我的 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;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-09
        • 2016-01-22
        • 2012-02-18
        • 1970-01-01
        • 2013-09-25
        • 1970-01-01
        • 1970-01-01
        • 2012-09-02
        相关资源
        最近更新 更多