Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

c# - programmatically make textblock with hyperlink in between text

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>

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?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...