- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有这个 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>
我想知道如何在 C# 中按程序复制它。
我知道如何在 C# 中创建 TextBlock
:
TextBlock tb = new TextBlock();
tb.Text="Some text"
而且我可以在 C# 中将多个 TextBlock
放在一个面板中。但我不明白你如何将 TextBlock
放入其他 TextBlock
中,并将 TextBlock
放入 Hyperlink
s 到 TextBlock
s。
是否有一些容器对象和额外的 TextBlock
对象以某种方式自动创建?或者 TextBlock
是否有一些允许它包含其他项目的方法/属性?
其他相关问题:
1. 向 Hyperlink
添加类似 Click() 事件的最佳方法是什么?
2. 有没有办法让蓝色的文字换行更干净?在上面的 XAML 中,只要最右边的单词需要换行,就会换行整个蓝色文本 block 。
感谢您提供的任何照明。
最佳答案
您可以修改通过 TextBlock's Inlines property 公开的内联集合.上面的 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 事件将事件处理程序挂接到每个超链接实例,但设置成本可能很高,并且会使用比必要更多的内存。相反,我建议利用路由事件并简单地将 RequestNavigate 事件挂接到所有超链接所在的容器。你可以这样做:
myContainer.AddHandler(
Hyperlink.RequestNavigateEvent,
new RequestNavigateEventHandler(
(sender, args) =>
{
/* sender is the instance of the Hyperlink that was clicked here */
}));
2A) 在您的 XAML 示例中,它将内部 TextBlock 视为需要全部包装在一起的元素。如果您使用我的基于运行的方法,包装应该从包含的文本 block 继承。
关于c# - 嵌套的文本 block 和超链接,如何在 C# 中复制此 XAML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1573382/
我是一名优秀的程序员,十分优秀!