简体   繁体   English

我无法获得UIElement的ActualSize

[英]I can't get ActualSize of an UIElement

I have an Image control, generated in runtime. 我有一个在运行时生成的Image控件。 It renders correct size when displaying. 它在显示时呈现正确的大小。 But I can't get size of that element. 但我无法得到那个元素的大小。 Width and Height is NaN. WidthHeight是NaN。 ActualWidth and ActualHeight is always 0.0 and control never fires SizeChanged event. ActualWidthActualHeight始终为0.0,控件永远不会触发SizeChanged事件。

在此输入图像描述

I'm also generating TextBoxes in the runtime and I can't get size of them too. 我也在运行时生成TextBoxes,我也无法获得它们的大小。

The code that generates image is bellow. 生成图像的代码如下。

ExtendedImage image = new ExtendedImage();
image.Name = "element" + item.Id;
if (item.Text.ToUpperInvariant().EndsWith(".GIF"))
{
    var gif = BookReader.Imaging.GIFDecoder.Decode(Application.GetResourceStream(new Uri("Files/Books/" + item.BookId + "/" + item.Text, UriKind.Relative)).Stream);
    image.Source = gif.Frames[0].Image;
}
else
{
    var img = new BitmapImage(new Uri("/Files/Books/" + item.BookId + "/" + item.Text, UriKind.Relative));
    image.Source = img;
}

image.SetValue(Canvas.LeftProperty, (double)item.LocationX);
image.SetValue(Canvas.TopProperty, (double)(Application.Current.Host.Content.ActualHeight - item.LocationY));

image.SizeChanged += (o, e) =>
{
    var sender = o as ExtendedImage;
    image.SetValue(UIElement.RenderTransformOriginProperty, new Point(0.5, 0.5));
};

image.InvalidateMeasure();

if (!item.Visible)
{
    image.Visibility = System.Windows.Visibility.Collapsed;
}

ContentPanel.Children.Add(image);

You can't access the size of the image before it's been rendered. 在渲染之前,您无法访问图像的大小。 And you can't render a item in a Canvas , without it having a explicit size. 如果没有明确的大小,您无法在Canvas渲染项目。

So your problem is that you're attempting to get the size of the image before it's actually been rendered. 所以你的问题是你在实际渲染之前试图获得图像的大小。

If the container of the Image has Height and Width , the image should have it as well. 如果Image的容器具有HeightWidth ,则图像也应具有HeightWidth Try to put your Image into a Grid or StackPanel and set the size explicitly. 尝试将您的Image放入GridStackPanel并明确设置大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM