以编程方式将行添加到文本块 [英] Adding a line to a textblock programmatically

查看:53
本文介绍了以编程方式将行添加到文本块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何通过调用 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);

这篇关于以编程方式将行添加到文本块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆