【问题标题】:Silverlight/WPF: Retreiving the size of a UIElement once it has been rendered on screenSilverlight/WPF:在屏幕上呈现 UIElement 后检索它的大小
【发布时间】:2011-02-24 09:48:09
【问题描述】:

我有以下简单的代码:

            var canvas = new Canvas();

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

                panel.Children.Add(textblock);

                textblock.Measure(infiniteSize);
            }

此时,我希望任何尺寸属性 (Height/Width, ActualHeight/ActualWidth, DesiredSize, RenderSize) 都能为我提供文本块的大小。他们都没有。

ActualHeight 总是给出16.0,无论字体大小。 ActualWidth 随文字长度变化,但不随字体大小变化。

我更改了父容器的字体大小,而不是 TextBlock 本身。

我觉得我缺少一些从代码隐藏中理解 Silverlight 元素操作的基本元素。

问题是:我如何获得TextBlock真实实际像素大小

【问题讨论】:

  • 1k 次观看但只有 1 次赞成?来吧伙计们!

标签: wpf silverlight size element


【解决方案1】:

下面是一个示例,它使用后面的代码将TextBlock 添加到Canvas,一旦呈现TextBlock,它就会在窗口标题中显示其高度。这就是你要找的吗?

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>

后面的代码:

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

【讨论】:

    【解决方案2】:

    您是否尝试过使用像Grid 这样的真实容器来代替Canvas? 如果您尝试使用Dispatcher.BeginInvoke 在Measure 之后读取ActualSize 属性怎么办?

    【讨论】:

    • 我想绝对定位容器内的文本块。为此,我使用Canvas.SetLeft()。我认为这不适用于Grid
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 2011-03-28
    • 2017-02-16
    相关资源
    最近更新 更多