WPF将图像添加到画布而不将它们添加为资源

时间:2014-10-06 20:22:10

标签: c# .net wpf canvas

我正在尝试将图像添加到我的WPF应用程序Canvas中。 据我所知,他们需要在VS解决方案中被引用为资源。 但是,我需要能够将图像复制到文件夹中,并且从XML文件中解析图像的相对Uri,并将图像加载到画布中:

    Image image = new Image();
    var pic = new BitmapImage();
    pic.BeginInit();
    pic.UriSource = new Uri(url, UriKind.Relative); // url is from the xml
    pic.EndInit();
    image.Source = pic;
    LayoutRoot.Children.Add(image); //since the image is not in VS marked as Resource,
    // nothing shows up

感谢您的善意建议

1 个答案:

答案 0 :(得分:1)

如果您指定URI的完整路径而不是使用UriKind.Relative uri,它将正常工作:

pic.BeginInit();
pic.UriSource = new Uri(@"C:\Path\To\File.jpg");
pic.EndInit();