Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在代码隐藏-Wpf中更改图像源_C#_Wpf_Imagesource - Fatal编程技术网

C# 在代码隐藏-Wpf中更改图像源

C# 在代码隐藏-Wpf中更改图像源,c#,wpf,imagesource,C#,Wpf,Imagesource,我需要动态设置图像源,请注意我的图像在网络上的某个地方,这是我的代码 BitmapImage logo = new BitmapImage(); logo.BeginInit(); logo.UriSource = new Uri(@"pack://application:,,,\\myserver\\folder1\\Customer Data\\sample.png"); logo.EndInit(); // Getting the exception here ImageViewer1.S

我需要动态设置图像源,请注意我的图像在网络上的某个地方,这是我的代码

BitmapImage logo = new BitmapImage();
logo.BeginInit();
logo.UriSource = new Uri(@"pack://application:,,,\\myserver\\folder1\\Customer Data\\sample.png");
logo.EndInit(); // Getting the exception here
ImageViewer1.Source = logo;
例外情况:

无法识别URI前缀


这里使用的包语法是针对作为应用程序中的资源包含的图像,而不是针对文件系统中的松散文件

您只需将实际路径传递到URI源:

logo.UriSource = new Uri(@"\\myserver\folder1\Customer Data\sample.png");

您只需要一行:

ImageViewer1.Source = new BitmapImage(new Uri(@"\myserver\folder1\Customer Data\sample.png"));
你们都错了! 为什么?因为您只需要以下代码即可工作:

(图像视图)/C#Img是:您的图像框

保持原样,不做任何更改(“ms appx://”)这是代码,不是您的应用程序名称 图像是项目中的文件夹,您可以对其进行更改。 dog.png是您文件夹中的文件,我也在文件夹“Images”和文件“dog.png”中使用 所以uri是:“ms-appx:///Images/dog.png" 我的代码是:



上述解决方案对我都不起作用。但这确实起到了作用:

myImage.Source = new BitmapImage(new Uri(@"/Images/foo.png", UriKind.Relative));

这些方法都不适用于我,因为我需要从文件夹中提取图像,而不是将其添加到应用程序中。 以下代码有效:

TestImage.Source = GetImage("/Content/Images/test.png")

private static BitmapImage GetImage(string imageUri)
{
    var bitmapImage = new BitmapImage();
    
    bitmapImage.BeginInit();
    bitmapImage.UriSource = new Uri("pack://siteoforigin:,,,/" + imageUri,             UriKind.RelativeOrAbsolute);
    bitmapImage.EndInit();
    
    return bitmapImage;
} 

+感谢你这么近。这也是唯一对我有用的东西。请注意,这在UWP中不起作用,因为UWP似乎只接受绝对Uri。我是这样做的:
myImage.Source=new-BitmapImage(新Uri(新Uri(Directory.GetCurrentDirectory(),UriKind.Absolute),新Uri(@/Images/foo.png),UriKind.Relative)))
这可能无法回答问题,但由于我的问题带我来到这里,这个答案对我来说很有效。我唯一遇到的问题是,png的透明度丢失了,似乎没有办法恢复它……我想说你们都错了,因为你们都没有提供一个完整的工作示例。这只是假设读者知道这些代码片段在代码中的位置。答案开头的轻率评论是不必要的。完整的工作答案,以及如何使用的说明都是必需的。
TestImage.Source = GetImage("/Content/Images/test.png")

private static BitmapImage GetImage(string imageUri)
{
    var bitmapImage = new BitmapImage();
    
    bitmapImage.BeginInit();
    bitmapImage.UriSource = new Uri("pack://siteoforigin:,,,/" + imageUri,             UriKind.RelativeOrAbsolute);
    bitmapImage.EndInit();
    
    return bitmapImage;
}