以编程方式将行添加到文本块
我知道如何通过调用 canvas.Childern.Add()
将控件添加到canvas/grid/layout.但是,当我想在文本块中嵌入某些内容时,似乎无法找到它的方法.文本块不包含 Add
方法或任何方法,所以我有点迷失了.
I know how to add a control to the canvas/grid/layout- simply by calling canvas.Childern.Add()
. However, when I want to embed something inside a textblock, I can't seem to find the method for it. A textblock doesn't contain a Add
method or anything, so I'm at a bit of a lost.
我要转换为C#的XAML是:
The XAML I'm trying to turn into C# is:
<TextBlock x:Name="textBlock">
<Line X1="0" Y1="0" X2="100" Y2="0" Stroke="Black" StrokeThickness="4" x:Name="line1"/>
<TextBlock Text="Hello there!" VerticalAlignment="Center" HorizontalAlignment="Center" x:Name="innerTextBlock" />
<Line X1="0" Y1="0" X2="100" Y2="0" Stroke="Black" StrokeThickness="4" x:Name="line2"/>
</TextBlock>
我认为做到这一点的最佳方法(除了答案)是简单地创建WPF用户控件并引用该控件.
I think the best way to do it (besides the answer) is to simply create a WPF User control and reference that.
您必须使用inlines属性(如前所述),以便再现您的xaml,足以执行以下操作(其中LayoutRoot是您的父控件的名称)):
You have to use inlines property (as stated before) so to reproduce your xaml it is enough to do the following (where LayoutRoot is the name of your parent control):
var t = new TextBlock();
t.Inlines.Add(new Line { X1 = 0, Y1 = 0, X2 = 100, Y2 = 0, Stroke = new SolidColorBrush(Colors.Black), StrokeThickness = 4.0 });
t.Inlines.Add("Hello there!");
t.Inlines.Add(new Line { X1 = 0, Y1 = 0, X2 = 100, Y2 = 0, Stroke = new SolidColorBrush(Colors.Black),StrokeThickness = 4.0});
LayoutRoot.Children.Add(t);