how to get BitmapImage in codebehind from the image tag in xaml in wpf/silverlight

后端 未结 2 1972
难免孤独
难免孤独 2021-01-24 07:36

i dont have a problem with binding a bitmapimage to image tag in codebehind for eg.

BitmapImage image = new BitmapImage();
imagetaginxaml.Source = image; // this         


        
2条回答
  •  误落风尘
    2021-01-24 08:30

    Well, Image.Source is of type ImageSource, there is no quarantee that it will be a BitmapImage, it may be though. If the source is created by the XAML parser it will be a BitmapFrameDecode (which is an internal class). Anyway, the only save assignment is:

    ImageSource source = img.Source;
    

    otherwise you need to cast:

    BitmapImage source = (BitmapImage)img.Source;
    

    which will throw an exception if the Source is not of this type. So you can either save-cast or try-catch:

    //(Possibly check for img.Source != null first)
    BitmapImage source = img.Source as BitmapImage;
    if (source != null)
    {
         //If img.Source is not null the cast worked.
    }
    
    try
    {
        BitmapImage source = (BitmapImage)img.Source;
        //If this line is reached it worked.
    }
    catch (Exception)
    {
        //Cast failed
    }
    

    You could also check the type beforehand using img.SourceisBitmapImage.

提交回复
热议问题