David Perlman
David Perlman

Reputation: 1470

Silverlight/WPF: Retreiving the size of a UIElement once it has been rendered on screen

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?

Upvotes: 1

Views: 1185

Answers (2)

Jeff Wilcox
Jeff Wilcox

Reputation: 6385

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?

Upvotes: 0

Wallstreet Programmer
Wallstreet Programmer

Reputation: 9677

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);
        }
    }
}

Upvotes: 2

Related Questions