我有一个WPF RichTextBox,其中isReadOnly
设置为True
。我希望用户能够单击RichTextBox中包含的HyperLink,而无需按住Ctrl。
除非按住Ctrl键,否则HyperLink上的Click事件似乎不会触发,因此我不确定如何继续。
我找到了解决方案。将IsDocumentEnabled设置为“ True”,并将IsReadOnly设置为“ True”。
<RichTextBox IsReadOnly="True" IsDocumentEnabled="True" />
一旦完成此操作,当我将鼠标悬停在HyperLink标记内显示的文本上时,鼠标就会变成“手”。没有保持控制权的点击将触发“点击”事件。
我正在使用.NET 4中的WPF。我不知道.NET的早期版本是否无法按照我上面的描述运行。
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的冒犯。
设法设法解决这个问题,很偶然。
加载到我的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文档中的链接。
您是否尝试过处理MouseLeftButtonDown事件而不是Click事件?
我从@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());
}
如果您想将箭头转换为手形光标总是没有默认系统导航,下面是方法。
<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;
}