c# - BitmapImage throws an initialization exception when file does not exist -


i have xaml this

<image x:name="myimage">     <image.source>         <bitmapimage urisource="{binding fullphotopath}"   cacheoption="onload" />     </image.source> </image> 

this works fine long fullphotopath exists. if not throws exception of

initialization of 'system.windows.media.imaging.bitmapimage' threw exception.

i realize can use image tag

to show image , if doesn't exist nothing displayed (and no exception thrown), far can tell syntax not allow me use cacheoption.

how can show nothing if image path not exist?

you use converter create bitmapimage whatever settings need can return null if see file doesn't exist , bind image.source through converter.

public class pathtobitmapimagelconverter : ivalueconverter {     public object convert(object value, type targettype, object parameter, cultureinfo culture)     {         string path = value string;          if (path == null || !file.exists(path))             return null;          var bmp =  new bitmapimage();         bmp.begininit();         bmp.cacheoption = bitmapcacheoption.onload;         bmp.urisource = new uri(path, urikind.relativeorabsolute);         bmp.endinit();         return bmp;     }       public object convertback(object value, type targettype, object parameter, cultureinfo culture)     {         throw new notimplementedexception();     } } 

make converter accessible somewhere

<local:pathtobitmapimagelconverter x:key="pathtobitmapimagelconverter"/> 

then use in xaml like

<image x:name="myimage" source="{binding fullphotopath, converter={staticresource pathtobitmapimagelconverter}}"/> 

Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -