以编程方式在文本之间创建带有超链接的文本块

mti*_*ijn 11 c# wpf textblock hyperlink

在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>
Run Code Online (Sandbox Code Playgroud)

现在我想摆脱整个TextBlock XAML并以编程方式添加该位.我没有创建TextBlock,将Text属性设置为'click please'并添加超链接TextBlock.Content.但是如何在"点击"和"请"之间定位超链接?如何将超链接的文本设置为"here"?

我没有太多的进展,到目前为止,我得到的是:

    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?
Run Code Online (Sandbox Code Playgroud)

Nas*_*ine 17

这是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);
Run Code Online (Sandbox Code Playgroud)

  • 你应该提出一个问题,你是否应该把它作为一个单独的问题提出来作为一个单独的问题. (7认同)