我有一个isReadOnly
设置为True
. 我希望用户能够单击 RichTextBox 中包含的超链接,而无需按住Ctrl.
除非被按住,否则 HyperLink 上的 Click 事件似乎不会触发Ctrl,所以我不确定如何继续。
我有一个isReadOnly
设置为True
. 我希望用户能够单击 RichTextBox 中包含的超链接,而无需按住Ctrl.
除非被按住,否则 HyperLink 上的 Click 事件似乎不会触发Ctrl,所以我不确定如何继续。
我找到了解决方案。将 IsDocumentEnabled 设置为“True”,并将 IsReadOnly 设置为“True”。
<RichTextBox IsReadOnly="True" IsDocumentEnabled="True" />
一旦我这样做了,当我将鼠标悬停在超链接标签中显示的文本上时,鼠标就会变成“手”。在不控制的情况下单击将触发“单击”事件。
我正在使用 .NET 4 中的 WPF。我不知道早期版本的 .NET 是否不能像我上面描述的那样运行。
JHubbard80的答案是一个可能的解决方案,如果您不需要选择内容,这是最简单的方法。
但是我需要 :P 这是我的方法:为 .s 中的 s 设置Hyperlink
样式RichTextBox
。本质是使用 aEventSetter
使Hyperlink
s 处理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 文档中的链接。
我从@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());
}
您是否尝试过处理 MouseLeftButtonDown 事件而不是 Click 事件?
如果您想在没有默认系统导航的情况下始终将箭头变成手形光标,以下是方法。
<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;
}