views:

204

answers:

2

I have the following simple piece of code:

            var canvas = new Canvas();

            foreach (var ztring in strings)
            {
                var textblock = new TextBlock();
                textblock.Text = ztring;

                panel.Children.Add(textblock);

                textblock.Measure(infiniteSize);
            }

At this point I would expect any of the size properties (Height/Width, ActualHeight/ActualWidth, DesiredSize, RenderSize) to give me the size of the textblock. None of them do.

ActualHeight always gives 16.0 no matter what size font. ActualWidth changes according to the text length but not the font size.

I change the font size on the parent container and not the TextBlock itself.

I feel like I am missing some basic element of understanding the manipulation of silverlight elements from within the codebehind.

The question is: how do I get the real actual pixel size of my TextBlock?

A: 

Have you tried using a real container like a Grid instead of Canvas? What if you try reading the ActualSize property after the Measure using a Dispatcher.BeginInvoke?

Jeff Wilcox
I want to absolute-position the textblocks within the container. For that I use `Canvas.SetLeft()`. I don't think that works for `Grid`.
ondesertverge
That said, within a `Grid` `DesiredSize` gives the same values as `ActualH\W` which isn't the same as the pixels be consumed on screen.
ondesertverge
+1  A: 

Below is a sample that adds a textblock to a canvas using code behind and once the textblock is rendered it displays its height in the title of the window. Is that what you are looking for?

XAML:

<Window x:Class="HeightTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300" Width="300">
    <StackPanel TextBlock.FontSize="30">
        <Canvas Name="_canvas" Height="200"/>
    </StackPanel>
</Window>

Code behind:

using System.Windows;
using System.Windows.Controls;

namespace HeightTest
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            TextBlock textBlock = new TextBlock();
            textBlock.Text = "Hello";
            Canvas.SetLeft(textBlock, 25);
            textBlock.Loaded += 
                (sender, e) => 
                {
                    Title = textBlock.ActualHeight.ToString();
                };
            _canvas.Children.Add(textBlock);
        }
    }
}
Wallstreet Programmer