Search code examples
c#.netwpfwidthtextblock

Can I know width of TextBlock when create it?


I create TextBox on the Canvas like this:

        TextBlock t = new TextBlock();
        t.Foreground = new SolidColorBrush(...);
        t.FontSize = 10;
        t.HorizontalAlignment = HorizontalAlignment.Left;
        t.VerticalAlignment = VerticalAlignment.Top;
        t.Text = ...;

        Canvas.SetLeft(t, "f(width)");
        Canvas.SetTop(t, ...);                

        canvas.Children.Add(t);

I want to know width of this TextBlock, because Left coordinate depends on this. Can I do it? ActualWidth is 0. Thanks.


Solution

  • Before you add it, call Measure on it, then use the DesiredSize.

    Edit: This is OK to do because Canvas does not affect the size of the element once placed. If you added it to, say, a Grid with a fixed-size row, this wouldn't give you the real Height once added since the adding to the Grid would change it.

    As Mario Vernari points out, if you have real complex positioning needs it's pretty easy to override ArrangeOverride (and sometimes MeasureOverride) and make a custom panel. Canvas is actually written this way, as is StackPanel, etc. They are all just specific-measuring and arranging panels, and you can make your own, too.