Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm using binding for source of an Image control.

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

But this ImageUri can be null, therefor I want to use a default image, a place holder, for that, which can be in /Assets/PlaceHolder.png for example.

How can I set a default image? thanks. (It's a WP8 app, but should not be different of WPF)

like image 200
user2715606 Avatar asked Aug 31 '13 00:08

user2715606


4 Answers

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>
like image 71
Nitesh Avatar answered Nov 20 '22 12:11

Nitesh


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>
like image 31
Shikhar Avatar answered Nov 20 '22 14:11

Shikhar


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));
}
like image 24
ZombieSheep Avatar answered Nov 20 '22 13:11

ZombieSheep


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>
like image 2
Hossein Narimani Rad Avatar answered Nov 20 '22 13:11

Hossein Narimani Rad