tags:

views:

50

answers:

2

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.

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>

EDIT: I think the best way to do it (besides the answer) is to simply create a WPF User control and reference that.

+3  A: 

I Believe if you have multiple lines you must use the Inlines property which is a collection that contains a list of inline elements. You can't directly add text to it, you must add it to an Inline object - such as a Run.

clocKwize
I tried `t.Inlines.Add(line);` where _t_ is a textblock and _line_ is a line. Then I added it to canvas but throws a _TargetInvocationError_.
DMan
I'm not at my computer right now, I'll have to take a look when I get to it! Is like a Run or a String? It should be a Run or something else that inherits from Inline I think.
clocKwize
Well, AFAIK, Run only supports text, which isn't what I'm looking for here.
DMan
as I said - anything that inherits from Inline... I was using a Run as a simple example.
clocKwize
+2  A: 

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);
tchrikch
Thanks, this worked perfectly! I actually had this code, but I got the _TargetInvocationError_, which was actually me being stupid and accidentally deleting `InitializeComponent();` which made it fail.
DMan