簡體   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