Change image source in code behind - Wpf

后端 未结 5 1796
醉酒成梦
醉酒成梦 2020-12-24 06:43

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.Begin         


        
相关标签:
5条回答
  • 2020-12-24 07:13

    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"));
        }
    
    0 讨论(0)
  • 2020-12-24 07:24

    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;
    } 
    
    0 讨论(0)
  • 2020-12-24 07:28

    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");
    
    0 讨论(0)
  • 2020-12-24 07:32

    You just need one line:

    ImageViewer1.Source = new BitmapImage(new Uri(@"\myserver\folder1\Customer Data\sample.png"));
    
    0 讨论(0)
  • 2020-12-24 07:39

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

    myImage.Source = new BitmapImage(new Uri(@"/Images/foo.png", UriKind.Relative));
    
    0 讨论(0)
提交回复
热议问题