c# - 以编程方式在文本之间制作带有超链接的文本 block

标签 c# wpf hyperlink textblock

在 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 属性设置为“请单击”并将超链接添加到 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?

最佳答案

这是在中间添加一个带有可点击链接的 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);

关于c# - 以编程方式在文本之间制作带有超链接的文本 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7890159/

相关文章:

c# - wpf 如何将转换器用于多绑定(bind)的子绑定(bind)?

javascript - 如果单击,将 href 文本添加到链接

java - 如何使 SWT 链接小部件中的文本可选择

wpf - 如何使用 MVVM 和 MVVM 工具包将属性绑定(bind)到文本框?

java - 在 JLabel 中的某些文本上监听 MouseEvents

c# - 从外部站点记录错误

从签名文件中获取 SignedCms 的 C# 实现

c# - 缓存可用于 WCF 和 ASP .NET 应用程序 (.NET 3.5)

c# - 如何在 Visual Studio 中调试具有类库输出类型的项目?

wpf - 在 Visual Studio 2008 XAML 设计器中引用嵌套类型