[英]Change image source in code behind - Wpf
I need to set image source dynamically, please note my image is in somewhere on the Network, here is my code我需要动态设置图像源,请注意我的图像在网络上的某个地方,这是我的代码
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;
Exception:例外:
The URI prefix is not recognized
URI 前缀无法识别
None of the above solutions worked for me.以上解决方案都不适合我。 But this did:
但这确实:
myImage.Source = new BitmapImage(new Uri(@"/Images/foo.png", UriKind.Relative));
你只需要一行:
ImageViewer1.Source = new BitmapImage(new Uri(@"\myserver\folder1\Customer Data\sample.png"));
The pack syntax you are using here is for an image that is contained as a Resource within your application, not for a loose file in the file system.您在此处使用的包语法是针对在应用程序中作为资源包含的图像,而不是针对文件系统中的松散文件。
You simply want to pass the actual path to the UriSource:您只需要将实际路径传递给 UriSource:
logo.UriSource = new Uri(@"\\myserver\folder1\Customer Data\sample.png");
None of the methods worked for me as i needed to pull the image from a folder instead of adding it to the application.没有一种方法对我有用,因为我需要从文件夹中提取图像而不是将其添加到应用程序中。 The below code worked:
以下代码有效:
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;
}
You are all wrong!你们都错了! Why?
为什么? Because all you need is this code to work:
因为您只需要此代码即可工作:
(image View) / C# Img is : your Image box (图像视图)/ C# Img 是:您的图像框
Keep this as is, without change ("ms-appx:///) this is code not your app name Images is your folder in your project you can change it. dog.png is your file in your folder, as well as i do my folder 'Images' and file 'dog.png' So the uri is :"ms-appx:///Images/dog.png" and my code :保持原样,不做更改(“ms-appx:///)这是代码,而不是您的应用程序名称图像是您项目中的文件夹,您可以更改它。 dog.png 是您文件夹中的文件,以及我做我的文件夹'Images'和文件'dog.png'所以uri是:“ms-appx:///Images/dog.png”和我的代码:
private void Button_Click(object sender, RoutedEventArgs e)
{
img.Source = new BitmapImage(new Uri("ms-appx:///Images/dog.png"));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.