日期:2014-05-20  浏览次数:21182 次

WPF用Image显示图片出错(为啥显示不出来?)
我是一个菜鸟,请大家帮我!

我想在WPF里用Image显示一个图片(a.png),这张图片存放在我的工程目录下(也就是跟工程所在的bin目录和obj目录同级),但当我尝试在Xaml中显示这张图片时,会出现错误,说:

文件a.png不是项目的一部分或其"Build Action"属性未设置为"Resource”.


我的代码是:
  <Image Source="pack://SiteOfOrigin:,,,/a.png"/>

当我把工程在Expression Blend中打开时,显示的错误是:未能找到文件"C:\Program Files\Microsoft Expression\Blend 2\a.png".


请问大家,上述问题是啥原因呢,我怎么解决呢?我有两个要求,第一点是不能把图片做为资源文件的形式引入到工程中进行编译(也就是跟工程没有任何关联);第二点是不能使用绝对路径。希望大家能帮帮我!

------解决方案--------------------
我能显示出来啊.
我也是用Expression Blend,进行的页面设计。
------解决方案--------------------
这个是Visual Designer的一个Bug,目前到SP1还没有修正。

异常是在PresentationCore.dll中的MS.Internal抛出来的,取路径错误。

据说最新的Blend修正了这个问题,不过我也没有具体测过。
使用Converter或者MarkupExtension去取图片是可以的

给你写了一个MarkupExtension

C# code

[MarkupExtensionReturnType(typeof(System.Windows.Media.Imaging.BitmapSource))]
[ContentProperty("Key")]
public class ImageSource : MarkupExtension
{
    public ImageSource()
        : base()
    {
    }
    public ImageSource(string key)
        : base()
    {
        Key = key;
    }

    public string Key
    {
        get;
        set;
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        BitmapImage bi = new BitmapImage();
        bi.BeginInit();
        bi.UriSource = new Uri(string.Format(@"{0}/{1}", Environment.CurrentDirectory, Key));
        bi.EndInit();
        bi.Freeze();

        return bi;
    }
}