单击RichTextBox中的超链接而无需按住CTRL-WPF

问题描述 投票:12回答:6

我有一个WPF RichTextBox,其中isReadOnly设置为True。我希望用户能够单击RichTextBox中包含的HyperLink,而无需按住Ctrl

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

wpf richtextbox click hyperlink ctrl
6个回答
24
投票

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

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

一旦完成此操作,当我将鼠标悬停在HyperLink标记内显示的文本上时,鼠标就会变成“手”。没有保持控制权的点击将触发“点击”事件。

我正在使用.NET 4中的WPF。我不知道.NET的早期版本是否无法按照我上面的描述运行。


13
投票

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

但是我需要:P这是我的方法:在Hyperlink内为RichTextBox设置样式。关键是要使用EventSetter来使Hyperlink处理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的冒犯。


5
投票

设法设法解决这个问题,很偶然。

加载到我的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文档中的链接。


0
投票

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


0
投票

我从@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());
}

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;
        }
© www.soinside.com 2019 - 2024. All rights reserved.