![](/img/trans.png)
[英]Bind RichTextBox without typing a lot of useless code or add HyperLinks to strings?
[英]Add clickable hyperlinks to a RichTextBox without new paragraph
是否可以在不創建新段落的情況下動態添加超鏈接,例如在此問題中動態添加到RichTextBox的超鏈接 ?
我想要類似“請訪問http://www.google.com 。謝謝!”之類的內容。 不
“請拜訪
。謝謝!”。
並且RichTextBox必須是只讀的,用戶不能鍵入它。 就像日志一樣,我需要定期添加一些有時包含URL的文本。
好,看起來這就是我需要的(感謝@Blam和@PaulN 動態地將超鏈接添加到RichTextBox ):
public MainWindow()
{
InitializeComponent();
rtb.IsDocumentEnabled = true;
rtb.Document.Blocks.FirstBlock.Margin = new Thickness(0);
}
private void AddHyperlinkText(string linkURL, string linkName,
string TextBeforeLink, string TextAfterLink)
{
Paragraph para = new Paragraph();
para.Margin = new Thickness(0); // remove indent between paragraphs
Hyperlink link = new Hyperlink();
link.IsEnabled = true;
link.Inlines.Add(linkName);
link.NavigateUri = new Uri(linkURL);
link.RequestNavigate += (sender, args) => Process.Start(args.Uri.ToString());
para.Inlines.Add(new Run("[" + DateTime.Now.ToLongTimeString() + "]: "));
para.Inlines.Add(TextBeforeLink);
para.Inlines.Add(link);
para.Inlines.Add(new Run(TextAfterLink));
rtb.Document.Blocks.Add(para);
}
private void button1_Click(object sender, RoutedEventArgs e)
{
AddHyperlinkText("http://www.google.com", "http://www.google.com",
"Please visit ", ". Thank you! Some veeeeeeeeeery looooooong text.");
}
但是還有一個小問題:也許有人知道如何刪除開頭的空白,該空白在上面的圖像中用紅線標記了嗎?
至於使RichTextBox或TextBox只讀
要添加文本,您可以使用運行
FlowDocument doc = new FlowDocument();
rtb.Document = doc;
rtb.IsReadOnly = true;
Paragraph para = new Paragraph();
doc.Blocks.Add(para);
Hyperlink link = new Hyperlink();
link.IsEnabled = true;
link.Inlines.Add("Hyperlink");
link.NavigateUri = new Uri("http://www.google.co.uk");
para.Inlines.Add(link);
Run run = new Run();
run.Text = " next words";
para.Inlines.Add(run);
你可以做到
<ContentControl>
<Span>
<Run Text="Please visit"/>
<Hyperlink NavigateUri="http://google.com">
<Run Text="google"/>
</Hyperlink>
<Run Text=". Thank you!"/>
</Span>
</ContentControl>
如果您在navigationFrame中,則可以免費獲得超鏈接功能
要么...
<StackPanel Orientation="Horizontal">
<TextBlock Text="Please visit"/>
<Button Style="linkButton" Content="Google" Command/Click="GotoGoogle"/>
<TextBlock Text=". Thank you!"/>
</StackPanel>
注意:通過執行以下操作,從RichText中刪除空白行:
MyRichTextBox.Document.Blocks.Clear();
添加段落運行時,在RichTextBox的開頭移動空白
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.