为什么在此示例中未触发ImageOpened事件?我在Win8的WinRT应用程序中使用它。
BitmapImage myImage = new BitmapImage();
myImage.ImageOpened += myImage_ImageOpened;
myImage.UriSource = new Uri("ms-appx:/Assets/Image.png");
private void myImage_ImageOpened(object sender, RoutedEventArgs e)
{
int pixelHeight = (sender as BitmapImage).PixelHeight;
}
我的问题是没有触发ImageOpened事件。我想检查图像的PixelHeight和PixelWidth,但如果我没有收到此事件,我就无法检查。
答案 0 :(得分:4)
WinRT具有延迟加载行为。除非您实际显示图像,否则图像将无法加载。如果您确实需要强制加载以执行某些布局调整,则可以使用这种变通方法来强制加载:
private async void Download()
{
Windows.UI.Xaml.Media.Imaging.BitmapImage image = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
image.ImageFailed += image_ImageFailed;
image.ImageOpened += image_ImageOpened;
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Logo.scale-100.png", UriKind.Absolute));
var stream = await file.OpenStreamForReadAsync();
await image.SetSourceAsync(stream.AsRandomAccessStream());
}
void image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
MessageDialog dg = new MessageDialog("Image Failed");
dg.ShowAsync();
}
void image_ImageOpened(object sender, RoutedEventArgs e)
{
MessageDialog dg = new MessageDialog("Image Opened");
dg.ShowAsync();
}