在XAML中,我有以下代码:
<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
。但是如何在“点击”和“请”之间定位超链接?如何将超链接的文本设置为“此处”?
我没有太多进展,到目前为止,我得到的是:
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?
答案 0 :(得分:15)
以下是添加TextBlock
并在中间添加可点击链接的代码:
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);