16

我有一个isReadOnly设置为True. 我希望用户能够单击 RichTextBox 中包含的超链接,而无需按住Ctrl.

除非被按住,否则 HyperLink 上的 Click 事件似乎不会触发Ctrl,所以我不确定如何继续。

4

6 回答 6

30

我找到了解决方案。将 IsDocumentEnabled 设置为“True”,并将 IsReadOnly 设置为“True”。

<RichTextBox IsReadOnly="True" IsDocumentEnabled="True" />

一旦我这样做了,当我将鼠标悬停在超链接标签中显示的文本上时,鼠标就会变成“手”。在不控制的情况下单击将触发“单击”事件。

我正在使用 .NET 4 中的 WPF。我不知道早期版本的 .NET 是否不能像我上面描述的那样运行。

于 2011-05-26T23:55:58.597 回答
16

JHubbard80的答案是一个可能的解决方案,如果您不需要选择内容,这是最简单的方法。

但是我需要 :P 这是我的方法:为 .s 中的 s 设置Hyperlink样式RichTextBox。本质是使用 aEventSetter使Hyperlinks 处理MouseLeftButtonDown事件。

<RichTextBox>
    <RichTextBox.Resources>
        <Style TargetType="Hyperlink">
            <Setter Property="Cursor" Value="Hand" />
            <EventSetter Event="MouseLeftButtonDown" Handler="Hyperlink_MouseLeftButtonDown" />
        </Style>
    </RichTextBox.Resources>
</RichTextBox>

在代码隐藏中:

private void Hyperlink_MouseLeftButtonDown(object sender, MouseEventArgs e)
{
    var hyperlink = (Hyperlink)sender;
    Process.Start(hyperlink.NavigateUri.ToString());
}

感谢gcores的启发。

于 2013-11-24T18:42:15.787 回答
6

设法找到解决这个问题的方法,几乎​​是偶然的。

加载到我的 RichTextBox 中的内容只是作为纯字符串存储(或输入)。我对 RichTextBox 进行了子类化,以允许绑定它的 Document 属性。

与该问题相关的是,我有一个看起来像这样的 IValueConverter Convert() 重载(对解决方案非必要的代码已被删除):

FlowDocument doc = new FlowDocument();
Paragraph graph = new Paragraph();

Hyperlink textLink = new Hyperlink(new Run(textSplit));
textLink.NavigateUri = new Uri(textSplit);
textLink.RequestNavigate += 
  new System.Windows.Navigation.RequestNavigateEventHandler(navHandler);

graph.Inlines.Add(textLink);
graph.Inlines.Add(new Run(nonLinkStrings));

doc.Blocks.Add(graph);

return doc;

这让我得到了我想要的行为(将纯字符串推入 RichTextBox 并获取格式),它还导致链接的行为类似于普通链接,而不是嵌入在 Word 文档中的链接。

于 2009-04-17T23:18:52.533 回答
1

我从@hillin 的回答中更改了 EventSetter。 MouseLeftButtonDown在我的代码(.Net 框架 4.5.2)中不起作用。

<EventSetter Event="RequestNavigate" Handler="Hyperlink_RequestNavigate" />
private void Hyperlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
{
    Process.Start(e.Uri.ToString());
}
于 2019-02-01T02:39:06.980 回答
0

您是否尝试过处理 MouseLeftButtonDown 事件而不是 Click 事件?

于 2009-04-17T22:52:45.247 回答
0

如果您想在没有默认系统导航的情况下始终将箭头变成手形光标,以下是方法。

<RichTextBox>
            <RichTextBox.Resources>
                <Style TargetType="{x:Type Hyperlink}">                                
                    <EventSetter Event="MouseEnter" Handler="Hyperlink_OnMouseEnter"/>
                </Style>                
            </RichTextBox.Resources>
</RichTextBox>


private void Hyperlink_OnMouseEnter(object sender, MouseEventArgs e)
        {
            var hyperlink = (Hyperlink)sender;
            hyperlink.ForceCursor = true;
            hyperlink.Cursor = Cursors.Hand;
        }
于 2019-11-28T08:59:36.207 回答