wpf - How to set a default source for an Image if binding source is null?

ID : 274330

viewed : 85

Tags : wpfxamlwindows-phone-7windows-phone-8wpf





Top 5 Answer for wpf - How to set a default source for an Image if binding source is null?

vote vote

99

You can achieve it by setting TargetNullValue

<Image>     <Image.Source>         <Binding Path="ImageUri" >             <Binding.TargetNullValue>                 <ImageSource>/Assets/PlaceHolder.png</ImageSource>             </Binding.TargetNullValue>         </Binding>     </Image.Source> </Image> 
vote vote

86

You can actually go the other way around which is a better experience in my opinion by simply using two Image controls in a Grid layout, one with the local placeholder source and one with the remote Binding. The local image is already there when you your remote binding is null. However if the binding is not null, it automatically covers the local placeholder image once it gets rendered.

<Grid>     <Image Source="Assets/Placeholder.png"/>     <Image Source="{Binding ImageUri}"/> </Grid> 
vote vote

75

You can set the ImageFailed event on your image,

<Image Source="{Binding ImageUri}" ImageFailed="Image_ImageFailed"/> 

and use the following C# to load a specific image in its place.

private void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e) {     ((Image)sender).Source = new BitmapImage(new Uri("/Assets/MyDefaultImage.png", UriKind.Relative)); } 
vote vote

60

You may try this:

<Image>     <Image.Source>         <Binding Path="ImageUri">             <Binding.TargetNullValue>                 <BitmapImage UriSource="/ProjName;component/Assets/PlaceHolder.png" />                                 </Binding.TargetNullValue>         </Binding>     </Image.Source> </Image> 
vote vote

60

You can use ImageFailed event and ChangePropertyAction.

This Code Snippet worked for me:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"  <Image x:Name="GeologyMapsLegend" Stretch="Fill" Height="150">     <i:Interaction.Triggers>         <i:EventTrigger EventName="ImageFailed">             <ei:ChangePropertyAction PropertyName="Source" TargetName="GeologyMapsLegend">                 <ei:ChangePropertyAction.Value>                     <ImageSource>                         /LanSysWebGIS;component/Pictures/Icon/NoImageAvailable.jpg                     </ImageSource>                 </ei:ChangePropertyAction.Value>             </ei:ChangePropertyAction>         </i:EventTrigger>     </i:Interaction.Triggers> </Image> 

Top 3 video Explaining wpf - How to set a default source for an Image if binding source is null?







Related QUESTION?