开发者

WPF: Solid color ImageSource

In my app I display images I get from external DLLs, by binding the Source of an Image control to a开发者_如何学Pythonn 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?


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;


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜