2

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.

2
  • I thought you do not have "width" in WPF. You have to use margins/padding to determine how it fits in it's container. What do you mean left coordinate depends on it? What are you trying to do? Commented Jul 21, 2011 at 15:53
  • @musefan There are Width and Height properties as well as ActuallWidth and ActualHeight Commented Jul 21, 2011 at 16:10

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

My vote here. However, it is not a good practice calling Measure before the element has been attached to the visual tree.
@Mario, True in some cases definitely, but when adding to a Canvas, the visual tree won't have an effect on the size, and you can pass a Size of +infinity, +infinity safely to Measure.
I know. You may do when your control has no children also, but I would discourage this practice. Instead, I prefer derive my own control from Canvas (or Panel), then write my custom positioning system. Much more elegant...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.