Canvas ImageSource不显示图像

时间:2014-06-25 13:19:37

标签: c# wpf image xaml wpf-controls

这是我的xaml:

<StackPanel Height="333">
    <Canvas x:Name="imageCanvas"
        RenderOptions.BitmapScalingMode="NearestNeighbor"
        RenderOptions.EdgeMode="Aliased">
        <Canvas.Background>
            <ImageBrush x:Name="image1"
                    Stretch="None"
                    AlignmentX="Left"
                    AlignmentY="Top">                                                     
            </ImageBrush>
        </Canvas.Background>                    
    </Canvas>
    <Canvas x:Name="overlayCanvas">
        <Rectangle Name="dummyRectangle" Width="1" Height="2" Fill="Transparent" />
    </Canvas>
</StackPanel>

这是我的C#代码:

void PlayImages()
{
    string testImageFolder = "C:\\TestImages";

    DirectoryInfo d = new DirectoryInfo(testImageFolder);//Assuming Test is your Folder
    FileInfo[] Files = d.GetFiles("*.tif"); //Getting Text files       
    image1.ImageSource = new BitmapImage(new Uri("C:\\TestImages\\ChanA_0001_0001_0001_0001.tif"));

}

但是,当上面的C#代码执行时,UI上什么也没发生。我想知道我应该在哪里更改以使图像显示出来?感谢。

2 个答案:

答案 0 :(得分:1)

是堆栈面板导致问题。我不知道为什么,但是如果删除了其中一些,那么图像会显示出来。删除了一些堆栈惩罚的xaml如下:

<StackPanel HorizontalAlignment="Left">
                <!--Controls:MenuControl/-->
                <Controls:ToggleButtonControl Margin="0,0,0,0" Height="43" RenderTransformOrigin="0.5,-0.233"  />
            </StackPanel>

            <Canvas x:Name="imageCanvas"
                    RenderOptions.BitmapScalingMode="NearestNeighbor"
                    RenderOptions.EdgeMode="Aliased" Margin="0,52,0,0">
                    <Canvas.Background>
                <ImageBrush x:Name="image1"
                                Stretch="None"
                                AlignmentX="Left"
                                AlignmentY="Top"
                               ImageSource="{Binding Path=Bitmap, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}">
                </ImageBrush>
                    </Canvas.Background>                    
                </Canvas>

答案 1 :(得分:0)

您的imageCanvas的宽度和高度始终为零,因为您既未添加任何子项,也未明确设置其WidthHeight

将您的XAML更改为仅使用一个Canvas,并可选择(取决于外部容器和要添加的子项)设置其WidthHeight属性:

<Canvas x:Name="overlayCanvas" Height="333" Width="500">
    <Canvas.Background>
        <ImageBrush x:Name="image1" ... />
    </Canvas.Background>                    

    <Rectangle ... />
</Canvas>