嵌套的TextBlocks和Hyperlinks,你如何在C#中复制这个XAML?

我有这个XAML:

  This is some Blue text.  This is some Green text following the Blue text.     

我想知道如何在C#中以程序方式复制它。

我知道如何在C#中创建TextBlock ,例如:

 TextBlock tb = new TextBlock(); tb.Text="Some text" 

我可以在C#中的一个面板中放置多个TextBlock 。 但我不知道如何将TextBlock放入其他TextBlock ,而将TextBlock放入Hyperlink放入TextBlock

是不是会自动创建一些容器对象和额外的TextBlock对象? 或者TextBlock是否有一些方法/属性允许它包含其他项?

其他相关问题:
1.将什么是Click()事件添加到Hyperlink的最佳方法是什么?
2.有没有办法让蓝色文字更干净地包裹? 在上面的XAML中,只要最右边的单词需要换行,就会包裹整个蓝色文本块。

感谢您提供的任何照明。

您可以修改通过TextBlock的Inlines属性公开的Inlines集合。 上面的XAML示例看起来像这样:

 TextBlock tb = new TextBlock { Text = "This is some Green text up front.", Foreground = Brushes.Green }; InlineCollection tbInlines = tb.Inlines; tbInlines.Add(new Run { Text = "This is some Blue text.", TextWrapping = TextWrapping.Wrap, Foreground = Brushes.Blue }); tbInlines.Add(new Run { Text = "This is some Green text following the Blue text." }); Run hyperlinkRun = new Run("And finally, this is a Hyperlink."); tbInlines.Add(new Hyperlink(hyperlinkRun)); 

至于你的相关问题:

1A)虽然可以使用类上的RequestNavigate事件将事件处理程序挂钩到每个单独的Hyperlink实例,但设置和使用的内存可能比必要的成本高。 相反,我建议利用路由事件,只需在所有超链接所在的容器上挂钩RequestNavigate事件。 你可以这样做:

 myContainer.AddHandler( Hyperlink.RequestNavigateEvent, new RequestNavigateEventHandler( (sender, args) => { /* sender is the instance of the Hyperlink that was clicked here */ })); 

2A)在你的XAML示例中,它将内部TextBlock视为需要一起包装的元素。 如果您使用的是基于Run的方法,则应该从包含的文本块inheritance包装。

我不知道TextBlocks,但这里是你如何在RichTextBox中做到这一点。 您可以使用RichTextBox而不是TextBlock。

  RichTextBox rtbTest = new RichTextBox(); rtbTest.IsDocumentEnabled = true; FlowDocument fd = new FlowDocument(); Paragraph para = new Paragraph(); Run r4 = new Run("Some Text To Show As Hyperlink"); Hyperlink h4 = new Hyperlink(r4); h4.Foreground = Brushes.Red; //whatever color you want the HyperLink to be // If you want the Hyperlink clickable h4.NavigateUri = new Uri("Some URL"); h4.RequestNavigate += new RequestNavigateEventHandler(h_RequestNavigate); // Leaving the two previous lines out will still make the Hyperlink, but it won't be clickable // use this if you don't want an underline under the HyperLink h4.TextDecorations = null; para.Inlines.Add(h4); fd.Blocks.Add(para); rtbTest.Document = fd; 

对于普通文本,我只使用了HyperLink,但删除了使其可点击的两行。 这会给文本带来颜色,但不会被点击。 虽然它仍然使光标变化。 虽然我确信有一个属性可以改变它。