2010-01-27 43 views
2

在我的應用程序中,我通過將圖像控件的源代碼綁定到ImageSource來顯示從外部DLL獲取的圖像。WPF:純色ImageSource

這很好,但有時我沒有從我的DLL中獲取任何數據,我只想顯示一個黑色的圖像。在這種情況下,我該如何創建一個只包含純色的ImageSource?

回答

0

的另一種方法是給一個背景色,並沒有顯示出圖像。

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

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

例如,您在模板中的某個位置有圖像,該圖像綁定到某些屬性照片。如果失敗,您可以返回空值。

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