2

在我的应用程序中,我通过将 Image 控件的 Source 绑定到 ImageSource 来显示从外部 DLL 获取的图像。

这很好用,但有时我没有从我的 DLL 中获得任何数据,我只想显示一个黑色图像。在这种情况下,如何创建仅包含纯色的 ImageSource?

4

2 回答 2

-1

例如,您在模板中的某处有图像,该图像绑定到某个属性 Photo。如果失败,您可以返回空值。

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

在您需要的资源中的某个地方

<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>
于 2010-01-27T17:49:32.820 回答
-1

另一种方法是提供背景颜色,而不显示图像。

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

// C#
imgDisplay.Source = null;
// -- OR --
imgDisplay.Visibility = Visibility.Collapsed;
于 2010-01-27T17:50:10.857 回答