A picture is worth a thousand words – so here is the existing against the desirable:

This is what I’ve tried w/o success:
public MainWindow()
{
InitializeComponent();
TextBlock txt = new TextBlock();
txt.Text = "asdsahd sakh uj";
txt.Background = Brushes.LightBlue;
Canvas.SetLeft(txt, 100);
container.Children.Add(txt);
Line line = new Line();
line.SetBinding(Line.X1Property, new Binding("Canvas.Left") {ElementName = "txt"});
line.X2 = line.X1;
line.Y1 = 0;
line.Y2 = 100;
line.StrokeThickness = 2;
container.Children.Add(line);
}
In the solution below, I assume that your
Canvashas a height and width that can change at runtime, and that yourTextBlockcan also have a height and width that change dynamically as well. The approach looks complicated, but its not. Of course doing this in XAML would be much, much more readable:TextBlockadd to canvas.Lineadd to canvas.MultiBindingto compute theCanvas.Leftproperty for theTextBlock. If either the width of theCanvasor theTextBlockchanges, this binding will re-evaluate and theIMultiValueConverterwill provide a new value. The value ofCanvas.Leftfor theTextBlockshould be:Canvas.ActualWidth/2–TextBlock.ActualWidth/2.Line.MultiBindingto compute theLine.Y2property for theLine. Assuming you want to draw the line to the bottom edge of theCanvas. To compute this:Canvas.ActualHeight–TextBlock.ActualHeight. The binding will re-evaluate if either change and theIMultiValueConverterwill provide a new value.Bindingto set theCanvas.Topproperty on theLine. In this example, theLineis drawn immediately below theTextBlock, so we can just bind toTextBlock.ActualHeight.TextBlock and Line Creation
MultiConverter to compute the length of the line
MultiConverter to center elements horizontally on the Canvas
Edit
To make the above code more clear – it really is just a 1-to-1 translation of the following XAML (using the
MultiValueConvertersfrom above):As you can see – if the canvas size changes, the text size changes, or the line thickness changes, the bindings ensure new values for
Canvas.LeftandCanvas.Topare computed.Hope this helps!