Question

In my app I display images I get from external DLLs, by binding the Source of an Image control to an ImageSource.

This works well, but sometimes I don't get any data from my DLL and I'd like to just show a black image. In that case, how do I create an ImageSource which contains just a solid color?

Was it helpful?

Solution

An alternative method is to give a background color, and not show the image.

// XAML
<Grid Background="Black">
  <Image x:Name="imgDisplay"/>
</Grid>

// C#
imgDisplay.Source = null;
// -- OR --
imgDisplay.Visibility = Visibility.Collapsed;

OTHER TIPS

for example you have image somewhere in template, which binds to some property Photo. In case of failure you can return null value.

<Image Source="{Binding Path=Photo, IsAsync=True, TargetNullValue={StaticResource EmptyImageDrawing}}"/>

And somewhere in resources you need

<DrawingImage
                x:Key="EmptyImageDrawing">
                <DrawingImage.Drawing>
                    <DrawingGroup>
                        <GeometryDrawing>
                            <GeometryDrawing.Brush>
                                <VisualBrush
                                    AlignmentX="Center"
                                    AlignmentY="Center"
                                    Stretch="None">
                                    <VisualBrush.Visual>
                                        <TextBlock
                                            Text="Failed to load photo"
                                            FontFamily="Calibri"
                                            FontSize="70"
                                            HorizontalAlignment="Center"
                                            VerticalAlignment="Bottom"
                                            TextAlignment="Center"
                                            TextWrapping="Wrap"/>
                                    </VisualBrush.Visual>
                                </VisualBrush>
                            </GeometryDrawing.Brush>
                            <GeometryDrawing.Geometry>
                                <RectangleGeometry
                                    Rect="0,0,1920,1080" />
                            </GeometryDrawing.Geometry>
                        </GeometryDrawing>
                    </DrawingGroup>
                </DrawingImage.Drawing>
            </DrawingImage>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top