【问题标题】:How to set Image source to Image in code behind如何在后面的代码中将图像源设置为图像
【发布时间】:2013-06-17 23:59:44
【问题描述】:

我无法在代码隐藏中设置 ImageSource。这是我的 XAML:

        <StackPanel Name="stkPanel" Height="1200" Width="478" HorizontalAlignment="Center" VerticalAlignment="Top" RenderTransformOrigin="0.723,0.509">
            <Image Loaded="imgPicture_Loaded_1" x:Name="imgPicture"   ImageOpened="ImgSelectedPicture_ImageOpened_1" Stretch="UniformToFill" Height="309" Width="413" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0,30,0,0"></Image>
        </StackPanel>

还有代码隐藏:

 private void imgPicture_Loaded_1(object sender, RoutedEventArgs e)
    {
        imgPict = (sender as Image);
        //ScrollViewer scroll = this.LayoutRoot.Children[2] as ScrollViewer;
        
        imgPict.Source = new BitmapImage(new Uri("/project;component/Images/avatar.png", UriKind.RelativeOrAbsolute));
        //bindPicture(imgPict);
        

    }

谁能看出我做错了什么?

【问题讨论】:

  • 您确定要显示的图像的BuildAction 设置为资源吗?您初始化图像Uri 的方式适用于嵌入式资源。最佳实践是使用Content 作为BuildAction 用于图像,Uri 初始化看起来像new Uri("/Images/avatar.png", UriKind.Relative)
  • 为什么要等设置图片源?您想解决或避免什么问题?

标签: image silverlight windows-phone-7 windows-phone-8


【解决方案1】:

首先,我不明白的是图像路径“/project;component/Images/avatar.png”不认为“;”符号使路径有效。这应该适合你:

<StackPanel Name="stkPanel" Height="1200" Width="478" HorizontalAlignment="Center"                 VerticalAlignment="Top" RenderTransformOrigin="0.723,0.509">
           <Image Loaded="imgPicture_Loaded" x:Name="imgPicture"  Stretch="UniformToFill"
             Height="309" Width="413" HorizontalAlignment="Center" VerticalAlignment="Top"             
             Margin="0,30,0,0"></Image>
 </StackPanel>

然后在后面的代码中

private void imgPicture_Loaded(object sender, RoutedEventArgs e)
 {
    imgPicture.Source = new BitmapImage(new 
                          Uri("/Images/StoreLogo.png",UriKind.Relative));                                        
 }

您可以将图像的“复制到输出目录”属性设置为“始终复制”。

【讨论】:

  • 最初使用的 URI 格式是有效的,并且允许在不同的程序集中引用资源。除非您在构建 XAP 文件后做一些不寻常的事情,否则设置“复制到输出目录”属性没有任何价值。它不会影响 XAP 文件。它是其他旧项目类型的遗留问题,您可能需要 build/bin 目录的全部内容。
猜你喜欢
  • 2012-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-19
  • 1970-01-01
  • 2010-10-20
相关资源
最近更新 更多