繁体   English   中英

WPF图像:未触发已加载事件

[英]WPF Image: Loaded event not being fired

我有WPF图片,并且已经订阅了一些事件:

<Image Grid.Row="0" 
       Source="{Binding Path=ImageSelected,  NotifyOnTargetUpdated=True, Converter={StaticResource imageToSourceConverter}}" 
       Visibility="{Binding imageVisibility}" 
       RenderTransformOrigin="0,0" 
       SnapsToDevicePixels="True" 
       MouseLeftButtonDown="myImage_MouseLeftButtonDown" 
       MouseLeftButtonUp="myImage_MouseLeftButtonUp" 
       MouseMove="myImage_MouseMove" 
       OverridesDefaultStyle="False"
       TargetUpdated="myImage_TargetUpdated"
       Cursor="Hand"
       RenderOptions.BitmapScalingMode="LowQuality" 
       RenderOptions.EdgeMode="Aliased" 
       Loaded="myImage_Loaded">

我注意到除Loaded事件外,所有事件均被触发,我不明白为什么。 我不知道它是否与其他事件冲突。 图像中触发的事件顺序是什么?

有什么想法为什么会发生吗?

您正在体验的是该事件的预期行为。

Loaded事件:

在元素被布置,渲染并准备好进行交互时发生。

我们正在谈论一个控制事件。 当控件(而不是您加载到其中的图像)被布置,渲染并准备好进行交互时,将触发此事件一次。

如果您正在寻找一个在加载图像本身时“告诉”您的事件,那么这不是正确的选择。

DownloadCompleted

如果这是您的需要,并且您显示的图像在本地不可用,而是通过HTTP下载的,则可以使用DownloadCompleted事件。 它由BitmapSource类提供。 这将需要您将Image控件绑定到BitmapSource,而不是提供和Uri ,我怀疑现在是这种情况。

自定义代码

我知道的唯一替代方法是手动执行此操作,这通常也为您提供了更大的灵活性。 以下是示例(未经测试的代码):

private void UpdateImageFromBuffer(byte[] yourBuffer)
{
    ThreadPool.QueueUserWorkItem(delegate {
        try {

            SelectedImageLoaded = false; // Set the notification Property and notify that image is being loaded.

            using (MemoryStream memoryStream = new MemoryStream(yourBuffer)) // Remember to provide the yourBuffer variable.
            {
                var imageSource = new BitmapImage();
                imageSource.BeginInit();
                imageSource.StreamSource = memoryStream;
                imageSource.EndInit();
                ImageSelected = imageSource; // Assign ImageSource to your ImageSelected Property.
            }

        } catch (Exception ex) {
            /* You might want to catch this */
        } finally {
            SelectedImageLoaded = true; // Notify that image has been loaded
        }
    });
}

首先,将图像的加载移至另一个线程,无论如何您都不希望在UI线程上执行此操作。 根据您需要处理“图像加载通知”,您需要修改上面的代码。

假设您要根据发生的事情更新UI,例如显示进度条或加载动画。 在这种情况下,上面的代码将SelectedImageLoaded属性设置为图像的当前状态。 您需要做的就是正确地将UI控件绑定到该Property以更新UI(注意: 类必须实现INotifyPropertyChanged )。

希望能有所帮助。

暂无
暂无

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

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