代码之家  ›  专栏  ›  技术社区  ›  Muhammad Akhtar

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

  •  35
  • Muhammad Akhtar  · 技术社区  · 15 年前

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

    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;
    

    例外情况:

    5 回复  |  直到 8 年前
        1
  •  68
  •   Diego Mijelshon    13 年前

    你只需要一句话:

    ImageViewer1.Source = new BitmapImage(new Uri(@"\myserver\folder1\Customer Data\sample.png"));
    
        2
  •  72
  •   Manindra Moharana    12 年前

    以上的解决方案都不适合我。但事实上:

    myImage.Source = new BitmapImage(new Uri(@"/Images/foo.png", UriKind.Relative));
    
        3
  •  5
  •   Wonko the Sane    15 年前

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

    只需将实际路径传递给UriSource:

    logo.UriSource = new Uri(@"\\myserver\folder1\Customer Data\sample.png");
    
        4
  •  3
  •   AustinWBryan ravenspoint    5 年前

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

    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
  •  -3
  •   voluntaryist7    8 年前

    你们都错了!

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

    图像是项目中的文件夹,您可以更改它。 所以uri是:“ms appx:///Images/狗.png" 我的密码是:


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