【问题标题】:AvalonEdit as a text viewer - no caretAvalonEdit 作为文本查看器 - 没有插入符号
【发布时间】:2017-04-27 09:39:07
【问题描述】:

我希望 AvalonEdit 成为一个文本查看器。

我可以:

textEditor.IsReadOnly = true;

并且该控件不允许进行任何更改,但它仍然像编辑器一样运行 - 显示插入符号,并使用导航键(箭头、向上/向下翻页)移动插入符号而不是滚动视图。

有没有办法让它成为一个查看器?或者至少隐藏插入符号?

【问题讨论】:

    标签: c# wpf avalonedit


    【解决方案1】:

    AvalonEdit 由三个组件组成:

    • TextEditor,将TextArea 包装在ScrollViewer 中,并添加高级TextBox 类API
    • TextArea,它采用 TextView 并添加插入符号、选择和输入处理
    • TextView,这是实际代码展示

    所以要禁用所有编辑功能,您可以直接使用TextView 类。要启用滚动,您需要自己将其包装在 ScrollViewer 中(重要:启用 CanContentScroll 以避免呈现文档的不可见部分)

    <ScrollViewer
           Focusable="False"
           CanContentScroll="True"
           VerticalContentAlignment="Top"
           HorizontalContentAlignment="Left">
        <avalonedit:TextView Name="textView" />
    </ScrollViewer>
    

    通过直接使用TextView 组件,您需要自己完成一些通常由TextEditor 完成的工作:

    textView.Document = new TextDocument(); // create document instance
    textView.LineTransformers.Insert(0,
        new HighlightingColorizer(HighlightingManager.Instance.GetDefinition("C#")));
    

    TextView 如果您想保留一些编辑功能(例如选择文本并将其复制到剪贴板)是不够的。 在这种情况下,您需要继续使用TextEditorTextArea,并禁用不需要的功能。

    您不能真正禁用插入符号,因为选择逻辑取决于插入符号,但您可以隐藏它:

    textEditor.TextArea.Caret.CaretBrush = Brushes.Transparent;
    

    将文档设为只读将禁用文本输入和各种编辑命令:

    textEditor.IsReadOnly = true;
    

    您可能还想从文本区域的输入处理程序中删除命令:

    // remove the keyboard caret navigation and selection logic,
    // but keep the mouse selection logic and editing commands
    textEditor.TextArea.DefaultInputHandler.NestedInputHandlers.Remove(
        textEditor.TextArea.DefaultInputHandler.CaretNavigation);
    

    【讨论】:

    • 感谢您的详细回答。那么添加行号的正确方法是什么? TextView 没有这个属性。尝试添加avalonedit:LineNumberMargin,但我不知道如何将其连接到文本视图。设置 TextView 属性会导致事情挂起。
    • 刚刚测试了 textEditor 方法,删除 CaretNavigation 后,滚动就像在真实查看器中一样工作。这是完美的,我可能最终会使用这种方法。
    【解决方案2】:

    尝试将IsHitTestVisible属性设置为false

    textEditor.IsHitTestVisible = false;
    

    它确实隐藏了插入符号,但很多事情不再起作用,即。用鼠标滚轮滚动

    如果您只想隐藏插入符号,可以将其CaretBrush 属性设置为Transparent

    textEditor.TextArea.Caret.CaretBrush = Brushes.Transparent;
    

    【讨论】:

    • 它确实隐藏了插入符号,但是很多东西不再起作用了,即。用鼠标滚轮滚动。
    猜你喜欢
    • 1970-01-01
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-07
    • 1970-01-01
    相关资源
    最近更新 更多