【问题标题】:Why ActualWidth and ActualHeight of an Image returns 0 after Loaded event?为什么图像的 ActualWidth 和 ActualHeight 在 Loaded 事件后返回 0?
【发布时间】:2019-10-04 13:04:30
【问题描述】:

我的窗口只包含一个Image 元素,例如这个,

<Image Width='255'
           Height='255'
           x:Name='img' Loaded='img_Loaded'/>

我想在加载图像时获取ActualWidthActualHeight 的值,但我得到了零。

如何在运行时获取这些值?

编辑

我正在尝试在 img_Loaded 处理程序中获取这些值。

        private void img_Loaded(object sender, RoutedEventArgs e)
        {
            int width = (int)img.ActualWidth;
            int height = (int)img.ActualHeight;
            // why zero?
        }

【问题讨论】:

  • 您必须在这些值更改之前加载图像。从docs阅读它
  • 你是对的@preciousbetine。我获取这些值的全部目的是创建一个WriteableBitmap,然后将其加载到图像中,但我想我可以先加载一个示例。

标签: c# wpf image


【解决方案1】:

如果您设置图像源,那么您将获得实际高度和实际宽度。

我试过了:

 <Image Name="img" Height="255" Width="250" Loaded="Image_Loaded" Source="delivery3.jpg"/>

    private void Image_Loaded(object sender, RoutedEventArgs e)
    {
        Debug.WriteLine($"ActualHeight {img.ActualHeight}");
    }

当然,实际高度为 255,因为高度设置为 255。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多