Change image source in code behind - Wpf

[亡魂溺海] 提交于 2019-11-30 10:55:37

问题


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


回答1:


You just need one line:

ImageViewer1.Source = new BitmapImage(new Uri(@"\myserver\folder1\Customer Data\sample.png"));



回答2:


None of the above solutions worked for me. But this did:

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



回答3:


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:

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



回答4:


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;
        } 



回答5:


You are all wrong! Why? Because all you need is this code to work:

(image View) / C# Img is : your Image box

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 :


private void Button_Click(object sender, RoutedEventArgs e)
    {
         img.Source = new BitmapImage(new Uri("ms-appx:///Images/dog.png"));
    }


来源:https://stackoverflow.com/questions/3787137/change-image-source-in-code-behind-wpf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!