私のアプリでは、ImageコントロールのソースをImageSourceにバインドすることにより、外部DLLから取得した画像を表示します。
これはうまく機能しますが、DLLからデータを取得できないことがあり、黒い画像を表示したいだけです。その場合、単色のみを含むImageSourceを作成するにはどうすればよいですか?
私のアプリでは、ImageコントロールのソースをImageSourceにバインドすることにより、外部DLLから取得した画像を表示します。
これはうまく機能しますが、DLLからデータを取得できないことがあり、黒い画像を表示したいだけです。その場合、単色のみを含むImageSourceを作成するにはどうすればよいですか?
たとえば、テンプレートのどこかに画像があり、それがいくつかのプロパティPhotoにバインドされています。失敗した場合は、null値を返すことができます。
<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>
別の方法は、背景色を指定し、画像を表示しないことです。
// XAML
<Grid Background="Black">
<Image x:Name="imgDisplay"/>
</Grid>
// C#
imgDisplay.Source = null;
// -- OR --
imgDisplay.Visibility = Visibility.Collapsed;