Skip to main content
 首页 » 编程设计

c#之我无法获得 UIElement 的 ActualSize

2024年02月23日17yxwkf

我有一个 Image 控件,在运行时生成。它在显示时呈现正确的大小。但我无法获得该元素的大小。 Width 和 Height 为 NaN。 ActualWidth 和 ActualHeight 始终为 0.0,控件永远不会触发 SizeChanged 事件。

我还在运行时生成 TextBox,但我也无法获取它们的大小。

生成图像的代码如下。

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

请您参考如下方法:

在图像呈现之前,您无法访问图像的大小。如果没有明确的尺寸,您就无法在 Canvas 中呈现项目。

所以你的问题是你试图在实际渲染之前获取图像的大小。