5 c# wpf xaml textblock hyperlink
我有这个XAML:
<TextBlock TextWrapping="Wrap" Foreground="Green"
Text="This is some Green text up front. ">
<TextBlock Foreground="Blue">
This is some Blue text.
</TextBlock>
This is some Green text following the Blue text.
<Hyperlink>
<TextBlock Text="And finally, this is a Hyperlink." TextWrapping="Wrap"/>
</Hyperlink>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)
我想知道如何在C#中以程序方式复制它.
我知道如何使用以下内容TextBlock在C#中创建s:
TextBlock tb = new TextBlock();
tb.Text="Some text"
Run Code Online (Sandbox Code Playgroud)
我可以TextBlock在C#中的一个面板中放置多个s.但我不看你怎么去把TextBlocks转换其他TextBlocks和TextBlocks转换Hyperlinks转换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));
Run Code Online (Sandbox Code Playgroud)
至于你的相关问题:
1A)虽然可以使用类上的RequestNavigate事件将事件处理程序挂钩到每个单独的Hyperlink实例,但是设置和使用比必要更多的内存可能代价高昂.相反,我建议利用路由事件,只需在所有超链接所在的容器上挂钩RequestNavigate事件.你可以这样做:
myContainer.AddHandler(
Hyperlink.RequestNavigateEvent,
new RequestNavigateEventHandler(
(sender, args) =>
{
/* sender is the instance of the Hyperlink that was clicked here */
}));
Run Code Online (Sandbox Code Playgroud)
2A)在你的XAML示例中,它将内部TextBlock视为需要将所有内容包装在一起的元素.如果您使用的是基于Run的方法,则应该从包含的文本块继承包装.
我不知道 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;
Run Code Online (Sandbox Code Playgroud)
对于普通文本,我只使用了超链接,但删除了使其可单击的两行。这将为文本提供颜色,但无法单击。尽管它仍然使光标发生变化。尽管我确信也有一个属性可以改变这一点。
| 归档时间: |
|
| 查看次数: |
4473 次 |
| 最近记录: |