以编程方式在文本之间创建带有超链接的文本块 [英] programmatically make textblock with hyperlink in between text
问题描述
在XAML中我有以下代码:
In XAML I have the following code:
<Label Width="120" Height="20" Name="label1" SnapsToDevicePixels="True" HorizontalAlignment="Left" VerticalAlignment="Bottom">
<TextBlock VerticalAlignment="Center" HorizontalAlignment="Left">
click
<Hyperlink RequestNavigate="Hyperlink_RequestNavigate" NavigateUri="foo">here</Hyperlink>
please
</TextBlock>
</Label>
现在我想摆脱整个TextBlock XAML并以编程方式添加该位。我创建TextBlock没有问题,将Text属性设置为'click please'并将超链接添加到 TextBlock.Content
。但是如何在点击和请之间定位超链接?如何将超链接的文本设置为这里?
Now I'd like to get rid of the whole TextBlock XAML and add that bit programmatically. I have no trouble creating the TextBlock, setting the Text property to 'click please' and adding a Hyperlink to TextBlock.Content
. But how do I position the Hyperlink in between 'click' and 'please'? And how do I set the text of the hyperlink to 'here'?
我没有太多进展,到目前为止,我得到的是:
I haven't got much going, so far all I got is this:
label2.Content = new TextBlock() { Text = "click please" };
//(label2.Content as TextBlock).Content does not exist?
//and even if it does.. how do I squeeze the hyperlink in between the text?
推荐答案
以下是添加 TextBlock
中间带有可点击链接:
Here's the code to add a TextBlock
with a clickable link in the middle :
Run run1 = new Run("click ");
Run run2 = new Run(" Please");
Run run3 = new Run("here.");
Hyperlink hyperlink = new Hyperlink(run3)
{
NavigateUri = new Uri("http://stackoverflow.com")
};
hyperlink.RequestNavigate += new System.Windows.Navigation.RequestNavigateEventHandler(hyperlink_RequestNavigate); //to be implemented
textBlock1.Inlines.Clear();
textBlock1.Inlines.Add(run1);
textBlock1.Inlines.Add(hyperlink);
textBlock1.Inlines.Add(run2);
这篇关于以编程方式在文本之间创建带有超链接的文本块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!